As the name implies, the template design pattern is to encapsulate a lot of common common code into a template, we only need to implement different business requirements of the code, and then combined with the template, so that the complete logic.

In our daily development, there are two common implementations of the template pattern: inheritance and interface callback. Let’s use these two methods to implement the template design pattern.



Consider a scenario where a piece of code looks like this:

public void doSomething(){fixed code snippet business related code fixed code snippet}Copy the code



If this code needs to be used in many places, and there is more fixed code and less business-related code, and it is more centralized, then if we write down a complete process every time we implement a business, there will be a lot of repeated code, using the template design pattern can solve this problem well.
Create a template class that encapsulates the template code:
public abstract class Templet {  public void doTemplet(){    System.out.println("Fixed code snippet"); // Business logic codedoSomething();        System.out.println("Fixed code snippet");  }    public abstract void doSomething(); }Copy the code


The class we need to use the template simply inherits the template class and implements the abstract method, so that when we call doTemplet, the business logic code we call is the implementation of our subclass, so that different logic implementations can use the same code.



To implement this with a callback, we first define a generic interface:


public interface Callback<V,T> {  public V doSomething(T t); }Copy the code



We’ll use the template’s test class:

public class Test {  public static void main(String[] args) {    useTemplet("Business Logic",new Callback<String, String>() {      @Override      public String doSomething(String t) {        returnt; }}); } public static void useTemplet(String str,Callback<String,String> callback){ System.out.println("Fixed code");        String result = callback.doSomething(str);        System.out.println(result );        System.out.println("Fixed code"); }} So that if there is any other code that needs to reuse the template, useTemplet is simply called.Copy the code


The template design pattern is widely used in framework design. For example, SpringMVC view is a typical template design pattern.