Template method mode (template mode)-hook method

Soy milk production problem

Write the program for making soy milk, and the instructions are as follows:

  1. Material selection for the production process of soymilk—>adding ingredients—>soaking—>put it in the soymilk machine to break

  2. By adding different ingredients, different flavors of soy milk can be made

  3. The steps of selecting materials, soaking and breaking them in the soymilk machine are the same for making soymilk of each flavor.

  4. please useTemplate method patternComplete (Note: Because the template method mode is relatively simple, it is easy to think of this program, so I use it directly, and no longer use the traditional program to lead to the template method mode)

Basic introduction to template method pattern

basic introduction

  1. Template Method Pattern (Template Method Pattern), also known as Template Pattern (Template Pattern), z in an abstract class publicly defines the template to execute its method. Its subclasses can rewrite the method implementation as needed, but the call will be made in the way defined in the abstract class.

  2. simply say,Template method patternDefine the skeleton of an algorithm in operation, and delay some steps to the subclass, so that the subclass can redefine some specific steps of the algorithm without changing the structure of an algorithm

  3. This type of design pattern is a behavioral pattern.

Template method pattern principle class diagram

Schematic class diagram of the template method pattern

Insert picture description here

  • Description of the principle class diagram-namely (the role and responsibilities of the template method pattern)
  1. AbstractClass abstract class, which implements the template method (template), defines the skeleton of the algorithm, and the concrete subclass needs to implement other abstract methods operationr2,3,4

  2. ConcreteClass implements the abstract method operationr2,3,4 to complete the steps of the characteristic subclass in the algorithm

The template method model solves the problem of soybean milk production

  1. Application example requirements
    Write the program for making soy milk, and the instructions are as follows:
    the process of making soymilk—>adding ingredients—>soak—>put it
    in the soymilk machine and break it. By adding different ingredients, you can make different flavors of soy milk
    . The steps to soymilk crushing are the same for making soymilk of each flavor (red beans, peanut soymilk...)
  2. Idea analysis and illustration (class diagram)
    Insert picture description here
  3. Code implementation
    client
public class Client {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//制作红豆豆浆
		
		System.out.println("----制作红豆豆浆----");
		SoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
		redBeanSoyaMilk.make();
		
		System.out.println("----制作花生豆浆----");
		SoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
		peanutSoyaMilk.make();
	}

}

Abstract class

//抽象类,表示豆浆
public abstract class SoyaMilk {
    
    

	//模板方法, make , 模板方法可以做成final , 不让子类去覆盖.
	final void make() {
    
    
		
		select(); 
		addCondiments();
		soak();
		beat();
		
	}
	
	//选材料
	void select() {
    
    
		System.out.println("第一步:选择好的新鲜黄豆  ");
	}
	
	//添加不同的配料, 抽象方法, 子类具体实现
	abstract void addCondiments();
	
	//浸泡
	void soak() {
    
    
		System.out.println("第三步, 黄豆和配料开始浸泡, 需要3小时 ");
	}
	 
	void beat() {
    
    
		System.out.println("第四步:黄豆和配料放到豆浆机去打碎  ");
	}
}

One of the subcategories

public class PeanutSoyaMilk extends SoyaMilk {
    
    

	@Override
	void addCondiments() {
    
    
		// TODO Auto-generated method stub
		System.out.println(" 第二步加入上好的花生 ");
	}

}

Hook method of template method pattern

  1. In the parent class of the template method pattern,We can define a method, it does not do anything by default, the subclass can override it depending on the situation, this method is called "hook". (Hook method, there are subclasses to implement subclasses, not to implement their own default)

  2. Let's use the example of making soy milk above. For example, we also want to make pure soy milk without adding any ingredients. Please use the hook method to modify the previous template method.

  3. Code demo:

Client:

public class Client {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//制作红豆豆浆
		
		System.out.println("----制作红豆豆浆----");
		SoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
		redBeanSoyaMilk.make();
		
		System.out.println("----制作花生豆浆----");
		SoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
		peanutSoyaMilk.make();
		
		System.out.println("----制作纯豆浆----");
		SoyaMilk pureSoyaMilk = new PureSoyaMilk();
		pureSoyaMilk.make();
	}

}

Abstract class: there are hook methods inside

/抽象类,表示豆浆
public abstract class SoyaMilk {
    
    

	//模板方法, make , 模板方法可以做成final , 不让子类去覆盖.
	final void make() {
    
    
		
		select(); 
		if(customerWantCondiments()) {
    
    
			addCondiments();
		}
		soak();
		beat();
		
	}
	
	//选材料
	void select() {
    
    
		System.out.println("第一步:选择好的新鲜黄豆  ");
	}
	
	//添加不同的配料, 抽象方法, 子类具体实现
	abstract void addCondiments();
	
	//浸泡
	void soak() {
    
    
		System.out.println("第三步, 黄豆和配料开始浸泡, 需要3小时 ");
	}
	 
	void beat() {
    
    
		System.out.println("第四步:黄豆和配料放到豆浆机去打碎  ");
	}
	
	//钩子方法,决定是否需要添加配料
	boolean customerWantCondiments() {
    
    
		return true;
	}
}

Soy milk (no ingredients are added by default)

public class PureSoyaMilk extends SoyaMilk{
    
    

	@Override
	void addCondiments() {
    
    
		// TODO Auto-generated method stub
		//空实现
	}
	
	@Override
	boolean customerWantCondiments() {
    
    
		// TODO Auto-generated method stub
		return false;
	}
 
}

Source code analysis of template method pattern in Spring framework application

  1. The template method pattern used when the Spring IOC container is initialized
  2. Code analysis + role analysis + description class diagram
    Insert picture description here
  3. Class diagram for source code (description of hierarchical relationship)
    Insert picture description here

Notes and details of the template method pattern

  1. The basic idea is:The algorithm only exists in one place, that is, in the parent class, easy to modify. When you need to modify the algorithm, as long as you modify the template method of the parent class or some steps that have been implemented, the subclass will inherit these modifications

  2. Maximize code reuse. The template method of the parent class and some steps that have been implemented will be inherited by the child class and used directly.

  3. 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, while the subclass provides the implementation of some steps.

  4. The shortcomings of this model: each different implementation requires a sub-class implementation, which leads to an increase in the number of classes and makes the system larger

  5. Generally, the final keyword is added to template methods to prevent subclasses from overriding template methods.

  6. Usage scenarios of template method mode:When to finish in a certain process, The process to perform a series of steps , 这一系列的步骤基本相同,但其个别步骤在实现时可能不同usually considered a method to handle with a template pattern

to sum up

Define an abstract parent class, which has a series of methods (One or two abstractOr haveDetermine whether you need an abstract class hook method) Encapsulated into a method, the subclass implements that abstract method, and the
client calls the subclass

Guess you like

Origin blog.csdn.net/weixin_46168350/article/details/111207364