This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge

0 x0, introduction

🤡 Nuggets August more text challenge begins again, liver up!! This paper deals with design patterns and patterns: behavioral patterns (58-59) and Template patterns (58-59), which are used to solve reuse and extension problems.

Tips: Second-hand knowledge processing is hard to avoid mistakes, interested in time can be consulted by themselves, thank you.


0 x1, definition

The original definition

Define the framework for the algorithm in the operation, deferring some steps to subclasses. The template method pattern lets subclasses redefine certain steps of the algorithm without changing the data structure.

Define the interpretation

The algorithm in the definition can be understood as business logic in the general sense, and not specifically the algorithm in the data structure and algorithm. The skeleton of the algorithm is the template, and the methods that contain the skeleton of the algorithm are the template methods, which is how the template mode pattern gets its name.

Don’t you get it? Write a simple example ~


0x2. Write a simple example

Or an example of a milk tea shop, the steps of a cup of milk tea can be divided into four steps: tea base → milk → feeding → packaging, which can be abstracted as an interface:

public interface ITea {
    void addTeaBase(a);
    void addMilk(a);
    void addIngredient(a);
    void pack(a);
}
Copy the code

AddMilk () and pack() can be replaced by abstract classes. The immutable parts are implemented in the parent class, and the mutable parts are implemented by the subclass line:

// Abstract the template
abstract class AbstractTea {
    // Select * from template; // Select * from template;
    abstract String addTeaBase(a);
    // Hook method → abstract template declaration and implementation, concrete template role can be implemented to extend;
    protected String addMilk(a) { return "Add milk"; }

    abstract String addIngredient(a);

    protected String pack(a) { return "Pack your drinks."; }

    // The template role is responsible for scheduling the basic method, which is usually final. The template role is not allowed to override
    final String make(a) {
        return addTeaBase() + "- >" + addMilk() + "- >" + addIngredient() + "- >"+ pack(); }}// The specific template
public class CoconutGreenTea extends AbstractTea {
    @Override String addTeaBase(a) { return "Add green tea base"; }
    @Override String addIngredient(a) { return "Add coconut nut toppings"; }}public class PearlBlackTea extends AbstractTea {
    @Override String addTeaBase(a) { return "Add black tea base."; }
    @Override protected String addMilk(a) { return "Add three flower evaporated milk"; }
    @Override String addIngredient(a) { return "Add pearl ingredients"; }}// Test case
public class TeaTest {
    public static void main(String[] args) {
        PearlBlackTea blackTea = new PearlBlackTea();
        System.out.println(blackTea.make());
        CoconutGreenTea greenTea = newCoconutGreenTea(); System.out.println(greenTea.make()); }}Copy the code

The code runs as follows:

This is the template method pattern. The code is very simple. In fact, the principle and implementation of most design patterns are very simple. Draw UML class diagrams, composition roles, usage scenarios, and advantages and disadvantages

Component roles:

  • AbstractClass → Defines all the steps in an “algorithm” and provides some common method logic;
  • ConcreteClass → Inherits the abstract template, rewriting some of the algorithm steps as needed;

Application scenarios

  • When multiple classes have the same method and common logic, the common behavior is extracted and concentrated into the common parent class to reduce code duplication.
  • The general algorithm, protocol and fixed process are designed as templates, and the algorithm steps or process steps are further optimized in each specific subclass.

advantages

  • Remove the repeated code in the subclass, abstract template to save the common code logic, subclass does not need to deal with the common logic repeatedly, only focus on the specific logic;
  • The subclass controls the reverse of the superclass, and decides whether to execute a certain step in the superclass algorithm through the subclass.
  • Code reuse, encapsulation, good scalability;

disadvantages

  • Violation of the open closed principle, “closed for modification”, the result of the subclass execution is affected by the parent class;
  • Increase the code reading difficulty, subclass jump will also be a lot of, not convenient to contact the context logic clues, the more steps in the template, the more difficult to maintain;
  • If a subclass is replaced in violation of the Richter substitution principle, the parent class may become unavailable or the whole logic may change.

0x3. Template pattern VS callback

The application scenarios of the two are consistent → define the algorithm skeleton and open the extension points to the outside world. Different places:

  • The template pattern is based on the implementation of inheritance relationship, the abstract method of the parent class is overridden by the subclass, the relationship between a class, different subclasses are defined for different implementations, and the subclass must implement all the abstract methods defined in the parent class;
  • Callbacks are implemented based on the composition relationship, which passes one object to another object, a relationship between objects. The callback object can be created using an anonymous class, without having to define the class in advance.

That’s all for this section. Thank you