What is a template pattern?

The Template Method pattern is defined as follows: Define a main line process business logic (abstract class), implement common methods in the parent class, define non-common methods as abstract methods, implement in different subclasses. So that subclasses can redefine certain steps without changing the main flow of the parent method. It’s a behavioral pattern.

The main advantages are as follows:

  1. It encapsulates the common part and extends the variable part. Sharing method superclass implementation, not sharing method definition abstract method, easy for subclass extension.
  2. The common part is removed from the parent class for easy code reuse.
  3. Some methods are implemented by subclasses, so subclasses can be extended to add functionality in accordance with the open closed principle.

The main disadvantages are as follows:

  1. Each time a special service is added, a new subclass inheritance is required, which leads to high complexity, abstract design, and increased system complexity.
  2. Abstract methods in the superclass are implemented by subclasses, whose execution affects the results of the superclass, leading to a reverse control structure (hooks – use them rarely, or you’ll be blamed for handing them over! – More on that later), which increases the complexity of the code logic and the readability of the code.
  3. This is the pain point of Abstract itself! If the parent class adds a new abstract method, all subclasses have to be changed again!

Attention! Attention! Attention! High energy ahead, here comes the practical scene! Dry goods.

Register template mode

1. Define a template class (abstract)

/** * @author **/ abstract class ShouyinTaiTemplate {public void main(String[] args) ShouyinTaiTemplate shouyinTaiTemplate = new JdPay(); shouyinTaiTemplate.templateMethod(); ShouyinTaiTemplate1 = new WeCartPay() shouyinTaiTemplate1.templateMethod(); } public void templateMethod() { getAuthor(); // Get the credential buildingMoney(); ConnectRpc (); // Call the three-party interface doPay(); Private void getAuthor() {system.out.println (" obtain the company account pay secret key: gongxifacai12345 "); } // Private void buildingMoney() {system.out.println (" gongxifacai12345, pay amount: 1 million "); } public void connectRpc();} public void connectRpc(); Private void doPay() {system.out.println (" pay successfully - pay amount: 1 million "); }}Copy the code

Step 2 Create two payment channel class inheritance templates

Subclasses of wechat Payment:

/** * @author **/ public class extends ShouyinTaiTemplate{@override public void connectRpc() { System.out.println(" call wechat pay interface successfully!" ); }}Copy the code

Subcategories of JD Pay:

/** * @author **/ public class JdPay extends ShouyinTaiTemplate {@override public void connectRpc() { System.out.println(" call jingdong pay interface successfully!" ); }}Copy the code

The result is as follows:

It can be seen from the result that all operations before and after payment are encapsulated in the parent class, and two subclasses are selected to implement specific RPC interface rules when calling the payment interface.

Using the above example, let’s analyze the structure of a template pattern.

The template method pattern contains the following primary roles

1. Abstract Class/Abstract template

Abstract template class that defines the main line business process methods. It consists of a template method and several basic methods. These methods are defined as follows.

(1) Template method: define the main process method, including the basic method in the order of business method.

(2) Basic methods: common basic methods, abstract basic methods, hook methods.

  • Abstract methods: declared in abstract classes and implemented by concrete subclasses.

  • Concrete methods: Already implemented in abstract classes, they can be inherited or overridden in concrete subclasses.

  • Hook methods: Implemented in abstract classes, including logical methods for judgment and empty methods that need to be overridden by subclasses.

2. Concrete Class

Concrete implementation classes, which implement abstract methods and hook methods defined in abstract classes, are part of a top-level logic.

Hook method (use less! Use less! Use less! Adds complexity)

It’s the same cash register demo

Define the template class

Public static void main(String[] args) {// // use jd.com payment method // ShouyinTaiTemplate shouyinTaiTemplate = new JdPay(); // shouyinTaiTemplate.templateMethod(); ShouyinTaiTemplate1 = new WeCartPay() shouyinTaiTemplate1.templateMethod(); } public void templateMethod() { getAuthor(); // Get the credential buildingMoney(); // Hook logic if(! MoneyMaxHook ()){// Exit the payment process if the payment channel amount red line system.out.println (" Payment process interrupted!" ); return; } connectRpc(); // Call the tripartite interface // hook special logic handles specialHook(); doPay(); Public Boolean moneyMaxHook() {return true;} public Boolean moneyMaxHook() {return true; Public void specialHook() {private void getAuthor() {public void specialHook() { System.out.println(" obtain company account payment secret key: gongxifacai12345 "); } // Private void buildingMoney() {system.out.println (" gongxifacai12345, pay amount: 1 million "); } public void connectRpc();} public void connectRpc(); Private void doPay() {system.out.println (" pay successfully - pay amount: 1 million "); }}Copy the code

2. Define two subclasses of payment method:

Subcategories of JD Pay:

/** * @author **/ public class JdPay extends ShouyinTaiTemplate {@override public void connectRpc() { System.out.println(" call jingdong pay interface successfully!" ); } @override public Boolean moneyMaxHook() {system.out.println (); Block payment "); return false; }}Copy the code

Subclasses of wechat Payment:

/** * @author **/ public class extends ShouyinTaiTemplate{@override public void connectRpc() { System.out.println(" call wechat pay interface successfully!" ); } @override public void specialHook() {system.out.println (" wechatpay trigger special logic! Surprise package!" ); }}Copy the code

If the subclass overwrites the value of the parent class, the hook returns:

If a subclass overrides an empty hook from its parent class, the hook returns:

Conclusion:

  • Use the template pattern as closely as possible to scenarios with fewer subclasses.
  • Use hook method as little as possible, later maintenance will be very difficult.