• 周五. 12月 9th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

23 design patterns (4) – template method design pattern

[db:作者]

1月 6, 2022

One . What is a template method design pattern

Understand literally , Template method is to define a set of methods , As a template , That’s the foundation . On this basis , We can process , Realize the realization of personalization . such as : Three meals a day . breakfast , Chinese food , dinner . Everyone has to eat three meals , But everyone may eat different meals . Three meals a day define the template — In the morning, in the middle and in the evening , Everyone’s three meals are the concrete realization of the template .

1.1 The purpose of the template method :

  1. Move invariant behavior from subclass to superclass , Removed duplicate code from subclasses .
  2. The structure of canonical subclasses

1.2 Definition of template method

Define the algorithm skeleton of an operation , And delay some steps of the algorithm to subclasses , So that the subclass can redefine some specific steps of the algorithm without changing the structure of the algorithm . It’s a kind of Behavioral patterns .

Two . Steps to define template methods

First step : Define template classes
The second step : Define specific subclasses
The third step : Client calls

Let’s take a look at each step :

2.1 Define template classes

Usually template classes are abstract classes , Responsible for giving the outline or framework of the algorithm . He has a number of Template method And a number of The basic method constitute .

  1. Template method

    The framework of the algorithm is defined , Defines the order of method calls , It contains one or more basic methods

  2. The basic method

    There are three types of basic algorithms :

    ​ a) Abstract method : Methods that subclasses must override . There is no default implementation .

    ​ b) The specific methods : The default implementation of the parent class definition , There is implementation logic , Can be inherited or overridden by specific subclasses

    ​ c) Hook method : There are two logical methods of judgment and empty methods that need subclass rewriting .

2.2 Define specific subclasses

Specific subclass , That is, the concrete implementation class , Implement abstract methods in abstract classes . They are an integral part of the abstract template approach .

2.3 Define client calls

The client calls the abstract class , Instantiate specific classes when instantiating , Just call the template method of the abstract class .

2.4 Let’s take a look at the relationship between abstract classes and subclasses UML Figure and source code implementation

  1. UML chart

It can be seen from the figure that the structure of abstract class can define three kinds of methods . There can be one or more . Subclasses must implement abstract methods in abstract classes , You can selectively override specific methods of the parent class . When subclasses implement interfaces , Think more about the six principles of design patterns .

  1. Source code

    Define the abstract class first , That’s the framework .

package com.lxl.www.designPatterns.templatePattern.template;
/**
* abstract class , Define templates
*/
public abstract class AbstractClass {
/**
* Define template method
* Standardizing the framework of the process
*/
public void templateMethod() {
// Call the specific method first
specificMethod();
// In calling abstract methods
abstractMethod();
}
/**
* The specific methods
*/
public void specificMethod() {
// Concrete public logic , The parent-child class is universal
System.out.println(" The specific methods --- General logic of parent-child class ");
}
/**
* Abstract method
*
* Abstract method , Subclasses must override
*/
public abstract void abstractMethod();
}

In defining specific implementation classes , Abstract methods that implement the parent class

package com.lxl.www.designPatterns.templatePattern.template;
/**
* Concrete implementation class
*/
public class ConcreteClass extends AbstractClass{
/**
* Override the abstract method of the parent class
*/
@Override
public void abstractMethod() {
System.out.println(" Concrete implementation class -- Override the abstract method of the parent class ");
}
}

Finally, define the client call

package com.lxl.www.designPatterns.templatePattern.template;
/**
* Template method client
*/
public class TemplateClient {
public static void main(String[] args) {
AbstractClass abstractClass = new ConcreteClass();
abstractClass.templateMethod();
}
}

Running results :

The specific methods — General logic of parent-child class
Concrete implementation class — Override the abstract method of the parent class

Design pattern according to template method , Let’s look at a specific case .

3、 … and 、 Case study

1. Case study 1: One day planning

Everyone has three meals a day , breakfast , Chinese food , Late ginseng . But everyone’s meals are different , Let’s take a look at everyone’s three meals , And what to do before and after three meals .

package com.lxl.www.designPatterns.templatePattern.oneDayArrangement;
/**
* Three meals a day
*/
public abstract class ArrangementAbstract {
/**
* Template method
* Set the framework for the day
*/
public void templateMethod() {
System.out.println(" The day is arranged as follows : ");
getUp();
breakfast();
lunch();
dinner();
getDown();
}
public void getUp() {
System.out.println(" Get out of bed ");
}
public void getDown() {
System.out.println(" sleep ");
}
/**
* Breakfast abstract class
*/
public abstract void breakfast() ;
/**
* Lunch abstract class
*/
public abstract void lunch();
/**
* Dinner abstract class
*/
public abstract void dinner();
}

Define three meals a day abstract class . Everyone’s schedule is , Get out of bed , breakfast , Chinese food , dinner , sleep . Getting up and going to bed is something everyone has to do , Three meals, too , But the food of the three meals is different , So we define three meals as abstract

One day schedule implementation class

package com.lxl.www.designPatterns.templatePattern.oneDayArrangement;
/**
* Zhang San's three meals a day
*/
public class PersonArrangement extends ArrangementAbstract{
private String name;
public PersonArrangement(String name) {
this.name = name;
}
/**
* Breakfast abstract class
*/
public void breakfast(){
System.out.println(name + "-- Have milk and bread for breakfast ");
}
/**
* Lunch abstract class
*/
public void lunch() {
System.out.println(name + "-- Chinese food in the canteen ");
}
/**
* Dinner abstract class
*/
public void dinner() {
System.out.println(name + "-- Fruit for dinner ");
}
}

Client calls

public class Client {
public static void main(String[] args) {
ArrangementAbstract zhangsan = new PersonArrangement(" Zhang San ");
zhangsan.templateMethod();
}
}

Running results :

The day is arranged as follows :
Get out of bed
Zhang San — Have milk and bread for breakfast
Zhang San — Chinese food in the canteen
Zhang San — Fruit for dinner
sleep

It can be seen that , Completely follow the steps of the template method .

2. Case study 2: Hook method

We said that up there , Template method design pattern , Basic methods include abstract methods , Specific methods and hook methods .
If you can use the hook method well , Can be perfectly implemented in the program subclass control the behavior of the parent class . Let’s look at the following case :

We define a hook method in the abstract method hookMethod(), In the template method templateMethod() in , Hook methods control the flow of code .

UML chart :

Source code :

package com.lxl.www.designPatterns.templatePattern.hookMethod;
/**
* abstract class , Define templates
*/
public abstract class AbstractClass {
/**
* Define template method
* Standardizing the framework of the process
*/
public void templateMethod() {
// Call specific methods
specificMethod();
// The hook method controls the next step
if (hookMethod()) {
// Call abstract method
abstractMethod();
}
}
/**
* The specific methods
*/
public void specificMethod() {
// Concrete public logic , The parent-child class is universal
System.out.println(" The specific methods --- General logic of parent-child class ");
}
/**
* Hook method
* The hook method has a concrete implementation ,
*/
public boolean hookMethod() {
return true;
}
/**
* Abstract method
*
* Abstract method , Subclasses must override
*/
public abstract void abstractMethod();
}

Define the concrete implementation

/**
* Concrete implementation class
*/
public class ConcreteClass extends AbstractClass {
/**
* Override the abstract method of the parent class
*/
@Override
public void abstractMethod() {
System.out.println(" Concrete implementation class -- Override the abstract method of the parent class ");
}
/**
* Hook method
* @return
*/
@Override
public boolean hookMethod() {
System.out.println(" Override the hook method of the parent class , Reverse controls the behavior of the parent class ");
return false;
}
}

Rewriting the hook method , Reverse controls the behavior of the parent class

public class TemplateClient {
public static void main(String[] args) {
AbstractClass abstractClass = new ConcreteClass();
abstractClass.templateMethod();
}
}

Running results

The specific methods — General logic of parent-child class
Override the hook method of the parent class , Reverse controls the behavior of the parent class

If subclass hook method HookMethod() Code changes , The running result of the program will also change .

Four . Advantages and disadvantages of the template approach

4.1 advantage

  1. Standardizing the framework , Encapsulates the unchanging part , Expanded the variable part . Parent class definition framework , And abstracts the common invariant part , Subclasses improve the implementation of the framework by rewriting and extending .
  2. Used ” Opening and closing principle “, Open to expansion , Turn off for changes . Subclasses can extend the implementation of the parent class by overriding the abstract methods of the parent class .
  3. There is parent control in the behavior set , Standardize the process

4.2 shortcoming

  1. Each implementation needs to define a concrete implementation class , Increase the number of classes , The system is more complex
  2. Disadvantages of inheritance , Once the parent class adds an abstract method , All subclasses need to be added . This goes against ” Opening and closing principle “.
  3. Abstract methods in the parent class are implemented by the child class , The execution result of the subclass affects the parent class , such ” Reverse control ” structure , It increases the complexity of the code .

5、 … and . Use scenarios

  1. The whole steps of the algorithm are fixed , But when individual parts are prone to change , Consider using the template approach to design patterns , Abstract the parts that are easy to change , Provide to subclasses to implement .
  2. When multiple subclasses have common behavior , It can be extracted and concentrated into a common parent class to avoid code duplication . First , To identify differences in existing code , And separate the differences into new operations . Last , Replace the different code with a template method that calls these new operations .
  3. When you need to control the extension of a subclass , Template methods only call hook operations at specific points , This allows only extension at these points .
  4. Refactoring , Template method pattern is a frequently used pattern , Extract the same code into the parent class , The hook function constrains its behavior

6、 … and . Thinking about the application of the six principles of design pattern

  1. Principle of single responsibility : A method has only one cause of change , It’s not easy to see , To open the specific implementation of subclass code
  2. Li substitution principle : Where a parent class appears, it can be replaced by a child class , And the results are consistent . The subclass overrides the method of the parent class . Template method design patterns may violate the principle of substitution , however , This is exactly what can “ Reverse control ” Principle
  3. Interface isolation principle : Depending on the smallest single interface , Not fat interfaces . accord with
  4. The principle of Dependence Inversion : Depend on abstraction , Rather than depending on the concrete . accord with
  5. Dimitar’s law : Minimum knowledge principle . Communicate with friends , Reduce communication with friends . It depends on whether the subclass implementation conforms to
  6. Opening and closing principle : Against the principle of opening and closing , Once the parent class adds an abstract method , All subclasses need to be added accordingly

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注