Template method pattern
Define the skeleton of an algorithm in a method and defer some steps to subclasses.
Template methods allow subclasses to redefine certain steps in an algorithm without changing the structure of the algorithm.
Each subclass must provide a complete implementation of the abstract steps in the template method
Hooks can be used in abstract parent classes to let subclasses decide whether certain steps need to be performed
tea and coffee
abstract parent class
package templateMethod; /** * Template method: * defines the steps of an algorithm * Allow subclasses to provide implementations for one or more steps */ public abstract class CaffeineBeverage { /** * Dominate everything, own the algorithm, and protect the entire algorithm */ final public void prepare() { boliWater (); brew(); pourInCup(); //Use hooks to affect the algorithm flow of abstract classes if(customerWantsCondiments()) { addCondiments(); } } /** * a hook * The default implementation is provided in the parent class * Subclasses can override the hook as needed * Note: Hook methods should not be modified as private! */ boolean customerWantsCondiments() { return true; } abstract void brew(); abstract void addCondiments(); void pourInCup() { System.out.println("Pouring into cup"); } void boliWater() { System.out.println("Boiling Water"); } }
Concrete Subcategory - Tea
package templateMethod; public class Tea extends CaffeineBeverage { @Override void brew() { System.out.println("Steeping the tea"); } @Override void addCondiments() { System.out.println("Adding Lemon"); } /** * Override hooks to provide your own functionality */ boolean customerWantsCondiments() { return false; } }
Concrete Subclass - Coffee
package templateMethod; public class Coffee extends CaffeineBeverage { @Override void brew() { System.out.println("Dripping Coffee through filter"); } @Override void addCondiments() { System.out.println("Adding Sugar and Milk"); } }
test
package test; import templateMethod.CaffeineBeverage; import templateMethod.Coffee; import templateMethod.Tea; public class TemplateMethodTest { public static void main(String[] args) { CaffeineBeverage tea = new Tea(); tea.prepare(); System.out.println("\n==================\n"); CaffeineBeverage coffee = new Coffee(); coffee.prepare(); } }