Template mode (16)

Believe in yourself, please believe in yourself

The previous chapter briefly introduced the proxy mode (15), if you haven’t read it, please watch the previous chapter

1. Template mode

Refer to the template pattern introduction in the rookie tutorial: https://www.runoob.com/design-pattern/template-pattern.html

In the template pattern (Template Pattern), an abstract class publicly defines the way/template to execute its methods.

Its subclasses can override the method implementation as needed, but calls will be made in the manner defined in the abstract class. This type of design pattern is a behavioral pattern.

1.1 Introduction

Intent: To define the skeleton of an algorithm in an operation, while deferring some steps to subclasses. The template method allows subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm.

The main solution is that some methods are common, but this method is rewritten in each subclass.

When to use: There are some general approaches.

How to solve it: Abstract these common algorithms.

Key code: implemented in the abstract class, and other steps implemented in the subclass.

Application examples:
1. When building a house, the foundation, wiring, and water pipes are all the same. Only in the later stage of construction are there differences such as adding closets and fences.
2. In Journey to the West, the Bodhisattva determined 81 difficulties. This is a top-level logical skeleton.
3. The support for Hibernate in spring encapsulates some established methods, such as opening a transaction, obtaining a session, closing a session, etc.
Programmers do not rewrite those codes that have been standardized, and can save them by directly throwing an entity.

Advantages: 1. Encapsulate the unchanged part and expand the variable part. 2. Extract public codes for easy maintenance. 3. The behavior is controlled by the parent class and implemented by the subclass.

Disadvantages: Each different implementation requires a subclass to implement, resulting in an increase in the number of classes and making the system even larger.

Usage scenarios: 1. There are methods shared by multiple subclasses, and the logic is the same. 2. Important and complex methods can be considered as template methods.

Note: In order to prevent malicious operations, general template methods are added with the final keyword.

image-20230615152323993

2. Template mode application

Define the skeleton of an algorithm in an operation and defer some steps to subclasses. Template methods allow subclasses to redefine some specific steps of the algorithm without changing the structure of the algorithm.

In layman's terms: There are a fixed number of steps to complete a thing, but each step is different according to the object, and the implementation details are different, you can
define a general method to complete the thing in the parent class, according to the needs of the completion event A step cloud calls the implementation method for each of its steps.
The specific implementation of each step is completed by subclasses.

2.1. Example of making milk

2.1.1 Definition of abstract class

@Slf4j
public abstract class Milk {
    
    

    public final  void make() {
    
    
        select();
        if (customerCondiments()) {
    
    
            addCondiments();
        }
        soak();
        beat();
    }
    void select() {
    
    
        log.info("第一步,选择好的黄豆");
    }

    // 添加信息,由子类去实现
    protected abstract void addCondiments();

    void soak() {
    
    
        log.info("第三步, 浸泡 3个小时");
    }

    void beat() {
    
    
        log.info("第四步: 打碎");
    }

    protected boolean customerCondiments() {
    
    
        return true;
    }

}

2.1.2 Different implementations

without any added

@Slf4j
public class NoMilk extends Milk{
    
    
    @Override
    protected boolean customerCondiments() {
    
    
        return false;
    }

    @Override
    protected void addCondiments() {
    
    

    }
}

For red beans:

@Slf4j
public class RedDou extends Milk{
    
    

    @Override
    public void addCondiments() {
    
    
        log.info("第二步,添加红豆");
    }
}

Peanuts:

@Slf4j
public class HuaShengMilk extends Milk{
    
    

    @Override
    public void addCondiments() {
    
    
        log.info("第二步,添加花生");
    }
}

2.1.3 Test verification

@Test
    public void oneTest() {
    
    
        Milk milk = new HuaShengMilk();
        milk.make();
    }

    @Test
    public void twoTest() {
    
    
        Milk noMilk = new NoMilk();
        noMilk.make();
    }

image-20230615152712879

2. Two examples of cooking

2.2.1 Cooking abstract class

public abstract class Food {
    
    

    public  void cookFood() {
    
    
        preparation();
        make();
        put();
        eat();
    }


    protected abstract  void preparation();

    protected abstract  void make();

    protected abstract void put();
    protected abstract  void eat();
}

2.2.2 Implement subclasses

make fish

@Slf4j
public class Fish extends Food{
    
    

    @Override
    protected void preparation() {
    
    
        log.info(">>> 准备买好的,已经处理过的活,简单再处理");
    }

    @Override
    protected void make() {
    
    
        log.info("烧水,把鱼放进去");
    }

    @Override
    protected void put() {
    
    
        log.info("把鱼放盘子里面,端上来");
    }

    @Override
    protected void eat() {
    
    
        log.info("吃鱼");
    }
}

The following article:

@Slf4j
public class Noodles extends Food {
    
    

    @Override
    protected void preparation() {
    
    
        log.info("准备面条,切葱花,烧开水");
    }

    @Override
    protected void make() {
    
    
        log.info("把面条放置滚水里面");
    }

    @Override
    protected void put() {
    
    
        log.info("捞出来,放碗里");
    }

    @Override
    protected void eat() {
    
    
        log.info("开始吃面条");
    }
}

2.2.3 Test verification

@Test
    public void foodTest() {
    
    
        Food food = new Fish();
        food.cookFood();

        food = new Noodles();
        food.cookFood();
    }

image-20230615152946745

advantage:

  1. The detailed steps are implemented in the subclass, and the subclass defines the detailed processing algorithm without changing the overall structure of the algorithm.
  2. Basic techniques for code reuse, especially important in database design
  3. There is a reverse control structure, which calls its subclass operations through a bow, and extends the parent class through subclasses to add new behaviors, which
    conforms to the principle of opening and closing.

shortcoming:

Each different implementation needs to define a subclass, which will lead to an increase in the number of classes, and the system will become huge.


The code for this chapter is placed on github:


https://github.com/yuejianli/DesignPattern/tree/develop/Template


Thank you for watching, if you like it, please follow me, thank you again!!!

Guess you like

Origin blog.csdn.net/yjltx1234csdn/article/details/131229104