Skip to content

Instantly share code, notes, and snippets.

@aonomike
Last active November 11, 2015 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aonomike/ef4f451f455c8c2c37ca to your computer and use it in GitHub Desktop.
Save aonomike/ef4f451f455c8c2c37ca to your computer and use it in GitHub Desktop.
Template Design Pattern and a Strategy Design Pattern

Template Design Pattern

Works with dependency inversion, which states that low level objects should not depend on high level objects Mainly used when objects follow a given sequence to perfom a task but the tasks are implemented differently in every object

//the abstract class, note that the manufacture function calls the abstract methods
public abstract class GeneralManufacturingProcess {
 public abstract void assembly();
 public abstract void test();
 public abstract void pack();
 public abstract void storage();
 
 public void manufacture() {
    this.assembly();
    this.test();
    this.pack();
    this.storage()
 }
}

public class Laptop extends GeneralManufacturingProcess {
  public void assembly(){
    //assembles laptop
  }
  
  public void test () {
    //tests laptops
  }
  
  public void pack() {
    //packs laptops
  }
  
  public void store() {
    //stores laptop
  }
}

public class App {
  public static void main(String [] args) {
    GeneralManufacturingProcess laptop = new Laptop();
    laptop.manufacture();
  }
} 

Strategy Design Pattern

Used with Open Closed Principle. Interface depended upon by client is defined in either Abstract class or Interface, and implementations are provided by classes extending or implementing the interface.

public abstract class Employee {
  abstract void performDuties();
}

public class Doctor extends Employee {
  private void performDiagnosis () { //perform diagnosis }
  private void prescribeDrugs () { //prescribe drugs }
  public void performDuties () {
    performDiagnosis();
    prescribeDrugs();
  }
}

public class HospitalManagement {
  public void callUpon(Employee employee) {
    employee.performDuties();
  }
}

public class App {
  public static void main(String... args) {
    Employee doctor = new Doctor();
    new HospitalManagement().callUpon(doctor);
  }
}

Note: Read more about Strategy anad Template design Patterns in order to refine notes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment