Java design pattern - Template Method Pattern

1, Introduction

The 23 design modes are roughly divided into three categories:

There are 5 kinds of creation modes: factory method mode, abstract factory mode, singleton mode, prototype mode and builder mode.

7 types (structural mode): adapter mode, decorator mode, agent mode, appearance mode, bridge mode, combination mode and sharing mode.

11 kinds of behavioral modes: strategy mode, template method mode, observer mode, iteration sub mode, responsibility chain mode, command mode, memo mode, status mode, visitor mode, mediator mode and interpreter mode.

Behavior type can be divided by the relationship between classes:

Basic introduction to template method mode:

  • Template Method Pattern, also known as template pattern, defines the template of the method executing it in an abstract class. Its subclasses can override the method implementation as needed, but the call will be made in the way defined in the abstract class.
  • In short, template method pattern defines the skeleton of an algorithm in operation, and delays some steps to subclasses, so that subclasses can redefine some specific steps of an algorithm without changing the structure of an algorithm. This type of design pattern belongs to behavioral pattern.

Two, template method mode

1. Schematic class diagram of template method mode

Description of schematic class diagram:

  • AbstractClass abstract class, which implements the template method and defines the skeleton of the algorithm. Specific subclasses need to implement other abstract methods operation2,3,4
  • ConcreteClass implements the abstract method, assuming operations 2, 3 and 4, to complete the specific business steps of the specific subclass in the algorithm

3, Specific needs

1. Soybean milk production

Prepare the procedure for making soybean milk as follows:

  • Process of making soybean milk: material selection - > adding ingredients - > soaking - > smashing in soybean milk machine

  • Different flavors of soybean milk can be made by adding different ingredients

  • The steps of selecting materials, soaking and smashing in the soybean milk machine are the same for making each flavor of soybean milk

Note: because the template method mode is relatively simple, it is easy to think of this scheme. Therefore, it is used directly instead of using the traditional scheme to export the template method mode

2. Template method mode scheme

Thought analysis - class diagram

Concrete implementation

// Abstract class representing soybean milk 	 SoyaMilk.java
public abstract class SoyaMilk {
	// Template method: it can be made into final and not be overwritten by subclasses
	final void make() {
		select();
		addCondiment();
		soak();
		beat();
	}
	
	//Material selection
	void select() { System.out.println("Step 1: choose fresh beans"); }
	//Add different ingredients: abstract methods, which are implemented by subclasses
	abstract void addCondiment();
	//soak
	void soak() { System.out.println("Step 3: soak the beans and ingredients 3 H"); }
	//Juicing
	void beat() { System.out.println("Step 4: put the beans and ingredients into the soybean milk machine for juice"); }
}

// RedBeanSoyaMilk.java
public class ReadBeanSoyaMilk extends SoyaMilk {
	@Override
	void addCondiment() {
		System.out.println("Step 2: add good red beans");
	}
}

// PeanutSoyMilk.java
public class PeanutSoyaMilk extends SoyaMilk {
	@Override
	void addCondiment() {
		System.out.println("Step 2: add good peanuts");
	}
}

// Client.java
public class Client {
	public static void main(String[] args) {
		System.out.println("=======Making red bean milk=======");
		SoyaMilk redBeanSoyaMilk = new ReadBeanSoyaMilk();
		redBeanSoyaMilk.make();
		
		System.out.println("=======Making peanut soybean milk=======");
		SoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
		peanutSoyaMilk.make();
	}
}

3. Hook method of template mode

In the parent class of the template method pattern, you can define a method that does nothing by default. The subclass can override it or not according to the situation. This method is called "hook". For example, we also want to make pure soybean milk without adding any ingredients. Please use the hook method to transform the previous template method. The code implementation is as follows:

// RedBeanSoyaMilk.java/PeanutSoyaMilk.java ibid., omitted

//Abstract class, representing soybean milk, SoyaMilk
public abstract class SoyaMilk {

	//Template method: it can be made into final and not be overwritten by subclasses
	final void make() {
		select();
		if(customerWantCondiment()) {
			addCondiment();
		}	
		soak();
		beat();
	}

	//1. Material selection
	void select() { System.out.println("Step 1: choose fresh beans"); }
	//2. Add different ingredients: abstract methods, which are implemented by subclasses
	abstract void addCondiment();
	//3. Soaking
	void soak() { System.out.println("Step 3: soak the beans and ingredients 3 H"); }
	//4. Juicing
	void beat() { System.out.println("Step 4: put the beans and ingredients into the soybean milk machine for juice"); }

	//Hook method: decide whether to add ingredients
	boolean customerWantCondiment() {
		return true;//Ingredients are added by default
	}
}

// PureSoyaMilk.java
public class PureSoyaMilk extends SoyaMilk {
	@Override
	void addCondiment() {
		// The method of adding ingredients is empty
	}
	@Override
	boolean customerWantCondiment() {
		return false;
	}
}

// Client.java
public class Client {
	public static void main(String[] args) {
		System.out.println("=Making pure soybean milk=");
		SoyaMilk pureSoyMilk = new PureSoyaMilk();
		pureSoyMilk.make();
	}
}

4, Precautions and details

  • The basic idea is that the algorithm only exists in one place, that is, in the parent class, which is easy to modify. When the algorithm needs to be modified, as long as the template method of the parent class or some implemented steps are modified, the child class will inherit these modifications

  • Benefits:

    • Maximize code reuse. The template method of the parent class and some implemented steps will be inherited by the child class and used directly;
    • It not only unifies the algorithm, but also provides great flexibility. The template method of the parent class ensures that the structure of the algorithm remains unchanged, and the implementation of some steps is provided by the child class
  • The deficiency of this pattern: each different implementation needs a subclass implementation, resulting in an increase in the number of classes and a larger system

    Note: the final keyword is added to general template methods to prevent subclasses from rewriting template methods

  • Usage scenario of template method mode:

    • When a process is to be completed, it needs to execute a series of steps, which are basically the same, but their individual steps may be different in implementation. It is usually considered to use the template method pattern

    • The template method mode can also be used to count the execution time of a piece of code: print the time before code execution in the front, and then print the time after code execution. The middle part is different execution codes

Keywords: Java Design Pattern

Added by suntra on Wed, 15 Dec 2021 01:40:32 +0200