There are feelings, there are dry goods, wechat search [three prince Ao bing] pay attention to the programmer who has a little bit of things.

This article has been included in GitHub github.com/JavaFamily, there are a line of large factory interview complete test sites, information and my series of articles.

Everyone will find every company, every company will have a standard, such as leave process specification, code specification and so on. Every company has this process, but the specific execution conditions are different.

The template method pattern in the design pattern can also be understood as a specification template. Mainly to improve the reuse of our code, and extension issues.

This template can also be used when licking dogs talk to their sisters, such as this template:

“Bao, XXXX, XXXX what XX? X you XXX”

When I get such a template, I can use it directly, we can directly fill in the parameters, such as:

“Bao, I have a vaccine, what vaccine, love you every second”

“Bao, I have made nucleic acid. What acid can I make? I can’t get your acid.”

“Treasure, today went to infusion, infusion of what liquid, miss you night”

.

But without further ado, template method patterns are also common in frameworks.

Today I’m going to talk specifically about the template method pattern in the behavioral design pattern.

Previous articles in the Design Patterns series:

  • The singleton pattern
  • The factory pattern
  • The process engine
  • Builder model
  • The prototype pattern
  • Chain of Responsibility model
  • Observer model
  • The strategy pattern

The outline

Or the old rules from the above five aspects to talk about the template method mode

define

What is the definition and purpose of the template method pattern?

  • Definition: The template method pattern defines an algorithm skeleton in a method and postpones certain steps to subclasses. The template method pattern lets subclasses redefine certain steps in an algorithm without changing the overall structure of the algorithm

  • Purpose: 1. The purpose of using the template method pattern is to avoid writing repetitive code so that developers can focus on the implementation of core business logic

    2. Resolve the inheritance contradiction between interfaces and interface implementation classes

    This is from Beauty of Design Patterns.

Structure:

  • AbstractTemplate: Defines a set of abstract methods, or implementation methods, or hook methods. That is, define the process
  • ConcreteTemplate: Implements a superclass abstraction method that implements different business logic code based on its own different template business logic. That is, the abstract methods implement the same, but the internal logic is different

The overall structure looks pretty simple, but it’s important to understand what the design pattern solves.

Code implementation? Let me give you an example.

Let’s take the above example for asking for leave. Assuming that company A needs the approval of its direct leadership and the notification of HR to ask for leave, Company B needs the approval of its direct leadership and the head of the department and the final notification of HR to complete the whole process of asking for leave. Then how to deal with this problem as OA office process? Look directly at the code implementation!

public abstract class AskForLeaveFlow {

    // Direct approval by the group leader
    protected abstract void firstGroupLeader(String name);

    // Level 2 Group leader Department head approval
    protected void secondGroupLeader(String name) {}// Tell HR that someone is off
    private final void notifyHr(String name) {
        System.out.println(Someone is asking for leave at present. The person asking for leave: + name);
    }

    // Leave flow template
    public void askForLeave(String name) { firstGroupLeader(name); secondGroupLeader(name); notifyHr(name); }}Copy the code

First of all, define a leave process, in which:

The firstGroupLeader method is abstract and must be implemented as a subclass

SecondGroupLeader approval, in the subclass can be overridden, or not overridden

NotifyHr is the notifyHr method and has been implemented internally

Finally, the askForLeave process method strings together the above template methods

public class CompanyA extends AskForLeaveFlow {
    
    @Override
    protected void firstGroupLeader(String name) {
        System.out.println("Someone in the CompanyA group asked for leave. The person asking for leave:"+ name); }}public class CompanyB extends AskForLeaveFlow {
    @Override
    protected void firstGroupLeader(String name) {
        System.out.println(CompanyB: Someone in group B is on leave. + name);
    }
    @Override
    protected void secondGroupLeader(String name){
        System.out.println(Someone is on leave in the CompanyB department.+ name); }}Copy the code

In CompanyA and CompanyB, the secondGroupLeader has the option of overwriting or not overwriting the class template method, referred to simply as the hook method.

public class testTemplate {
    public static void main(String[] args) {
        // Company A leave process template
        AskForLeaveFlow companyA = new CompanyA();
        companyA.askForLeave("AoBing");
        // Result: someone in CompanyA asked for leave
        // There are some people asking for leave

        AskForLeaveFlow companyB = new CompanyB();
        companyB.askForLeave("AoBing");
        // Result: There was a leave in CompanyB group. The person on leave was aobing
        // CompanyB: Someone is asking for leave
        // There are some people asking for leave}}Copy the code

Finally, the test dome results. CompanyA and companyB output corresponding leave procedures respectively.

As you may have noticed, template methods can have abstract methods as well as concrete implementation methods and hook methods.

Therefore, you can consider whether to define the template method internally as an abstract method or something else in the application process.

Applications in the framework

The template method pattern is also very common in our common Java frameworks, but we may not be aware of it.

The first one: first of all, when we learn SpringMVC, we will write some servlets at the beginning to handle some POST or GET requests.

Here is a direct look at the source code you can see that this is also the idea of using the template method pattern directly, during the HttpServlet inheritance GenericServlet is also the embodiment of the template method, which shows that the template can be abstracted multiple times.

InputStream, OutputStream, Reader, Writer, etc. of Java IO classes can be seen in the template method pattern.

InputStream is an InputStream method that uses the read template method.

Of course, there are many others in the IO class, I will not a paste source code out, interested students, you can open the source code to understand.

Business, for example,

How do you use the template approach in business?

The first thing you need to understand about the template approach is that it exists to make your code more reusable and extensible, so with that in mind I’ll give you an example.

Before I wrote the chain of responsibility model to give you an example of the commodity details, this time I still use the commodity details, but use the template method mode to achieve this problem, understood as the detailed version 2.0.

We can display product details in modules, such as head diagram, product information, SKU information, delivery address, installment payment and so on.

So how to assemble to the display of product details?

Flow chart:

You can see a request coming in, and you can have the module assembler choose to assemble and return the result.

To mention one point, in order to reduce the request time of the whole link when requesting the module in the second step, we can consider serial or parallel (open thread pool processing).

So let’s go straight to the code

public abstract class AbstractTemplateBlock<T> {
    // Result of assembly
    public T template(ModelContainer modelContainer) {
        T block = initBlock();
        try {
            this.doWork(modelContainer, block);
        } catch (Exception e) {
            // You can choose to catch exceptions, interrupt the process, or just print logs without interrupting the process
        }
        return block;
    }
    // Initialize the build return result model
    protected abstract T initBlock(a);
    // Define the abstract template
    protected abstract void doWork(ModelContainer modelContainer, T block) throws Exception;
}
Copy the code

Let’s create the template Block first

@Component
public class ItemInfoBlock extends AbstractTemplateBlock<ItemInfoBlock.ItemInfo> {
    @Override
    protected ItemInfoBlock.ItemInfo initBlock(a) {
        return new ItemInfoBlock.ItemInfo();
    }

    // Simulate business logic, assemble and return commodity information module data
    @Override
    protected void doWork(ModelContainer modelContainer, ItemInfo block) throws Exception {
        block.setItemId(123L);
        block.setItemName("Test");
    }
    @Data
    public static class ItemInfo {
        private Long itemId;
        privateString itemName; }}Copy the code

There’s only one ItemInfoBlock here, and the other modules are written the same way, so I won’t write it all.

    public static void main(String[] args) {
        // 1. Simulate getting the SpringBean
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        ItemInfoBlock itemInfoBlock = (ItemInfoBlock) applicationContext.getBean("itemInfoBlock");

      // 2. ModelContainer can be understood as request parameters that run through the context, or some preloaded data that is required to assemble the data
       ModelContainer modelContainer  = new ModelContainer();
       // 3. Get the return result
       ItemInfoBlock.ItemInfo itemInfo = itemInfoBlock.template(modelContainer);
       System.out.println(JSON.toJSONString(itemInfo));
       {"itemId":123,"itemName":" test "}
    }
Copy the code

Each module contains an AbstractTemplateBlock containing an abstract doWork method that subclasses the current business logic.

And when you get the results back in step 3, I’m just listing them separately, so you can make changes depending on the situation. For example, return a map structure. MapKey is the module name and value is the data.

The current model of assembling commodity details is also a more common way. The code has high reusability and scalability, which conforms to the idea of template method mode.

conclusion

We can also understand the characteristics of the template method mode, the applicable scenario is to increase the reuse of code, and scalability.

Again, there is nothing wrong with writing code that is not nested because of design patterns. Reasonably learn how each design pattern fits the scene and what problems it solves.

Bao, I may not be able to update normally tomorrow, I’m sick and on fluids.

I’m Aobing, the more you know, the more you don’t know, thank you for your talent: likes, favorites and comments, we’ll see you next time!


This article is constantly updated. You can search “Santaizi Aobing” on wechat and read it for the first time. Reply [Information] There are the interview materials and resume templates for first-line big factories prepared by me.