"Head First Design Pattern": Template Method Pattern

Template method pattern


Definition : The Template Method pattern defines the skeleton of an algorithm in a method, while deferring some steps to subclasses. Template methods allow subclasses to redefine certain steps in an algorithm without changing the structure of the algorithm. A template method is a fixed-step "algorithmic" skeleton method. The variable part of this algorithm is implemented through inheritance, with overloading in subclasses. In this way, while the skeleton of the algorithm remains unchanged, the detailed steps of the algorithm can be adapted according to different needs. The class diagram is as follows:
"Head First Design Pattern": Template Method Pattern


Advantages :
● Template method pattern defines a set of algorithms, and delegates the specific implementation to subclasses.
● Template method pattern is a basic technique of code reuse.
● The template method pattern leads to a reverse control structure, in which a parent class invokes the operations of its subclasses, and new behaviors are added by extending the subclasses, conforming to the "Open-Closed Principle".


Disadvantages :
● Each different implementation needs a subclass to implement, which leads to an increase in the number of classes and a larger system.


Usage scenarios :
● Implement the invariant part of an algorithm once, and leave the variable behavior to subclasses.
• Behavior common to subclasses should be extracted and concentrated into a common parent class to avoid code duplication.
● Control the extension of subclasses.


Case 1 : There are many common steps for making tea and coffee, as follows:
● Boil water
● Add tea leaves to brew (coffee powder)
● Add seasonings (such as honey, lemon, sugar) as needed ● Pour the brewed
tea into a cup
The tea code is as follows (coffee is similar, so it is omitted):

public class Tea {
   // 执行步骤
   void prepareRecipe() {
      boilWater();
      steepTeaBag();
      pourInCup();
      addLemon();
   }
   public void boilWater() { System.out.println("Boiling water");}
   public void steepTeaBag() {System.out.println("Steeping the tea"); }
   public void addLemon() { System.out.println("Adding Lemon"); }
   public void pourInCup() { System.out.println("Pouring into cup");}
}

It is not difficult to find that the code in these two classes is repeated a lot. The steps are the same, we can encapsulate it, and we use the template method pattern to modify it, as follows:
Template method code:

public abstract class CaffeineBeverage {
   final void prepareRecipe() {
      boilWater();
      brew();
      pourInCup();
      addCondiments();
   }
   abstract void brew();
   abstract void addCondiments();
   void boilWater() {
      System.out.println("Boiling water");
   }
   void pourInCup() {
      System.out.println("Pouring into cup");
   }
}

Bubble tea code:

public class Tea extends CaffeineBeverage {
    public void brew() {
        System.out.println("Steeping the tea");
    }
    public void addCondiments() {
        System.out.println("Adding Lemon");
    }
}

Summary : The subclass can flexibly implement the specific logic of each step, and the execution step is determined by the prepareRecipe() method in the abstract class.


Case 2 : The use of hooks. The hook is a boolean state that controls whether a certain step code needs to be executed in prepareRecipe() (subclasses modify it by themselves), as follows:

public abstract class CaffeineBeverageWithHook {
   void prepareRecipe() {
      boilWater();
      brew();
      pourInCup();
      if (customerWantsCondiments()) {
         addCondiments();
      }
   }
   abstract void brew();
   abstract void addCondiments();
   void boilWater() { System.out.println("Boiling water");}
   void pourInCup() { System.out.println("Pouring into cup"); }
  // 钩子方法
    boolean customerWantsCondiments() {
      return true;
   }
}

Template method pattern in Java:
● Applet
● JFrame in Swing
● java.io.InputStream, java.io.OutputStream, java.io.Reader and all non-abstract methods in java.io.Writer.
● java.util.AbstractList, java.util.AbstractSet and all non-abstract methods in java.util.AbstractMap.


Design principle: good rookie principle, don't find us, we will find you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324956740&siteId=291194637