Twenty-three Classical Design Patterns-32-Template Method Patterns

1. Template Method Pattern

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without chaging the algorithm's structure. (Define a framework for an operation algorithm, and defer some steps to a subclass implementation so that the subclass does not The structure of the algorithm can be changed and only the specific steps can be redefined.

1.1 Core Ideas

1.2 Template Method Patterns-Class Diagrams

Template method class diagrams are relatively simple, with only two roles

  • AbastractClass: Abstract class. Responsible for defining template methods and concrete steps:
    • Template Method: Multiple definitions can be defined, usually modified with final modifiers to prevent subclass tampering algorithms
    • Step Method: Usually defined as an abstract method, implemented by subclasses. Protected modification is usually used to allow access to subclasses only. (Note that when protected modification is used in java language, other classes under the same package can also be used.)
    • Hook method: Provides default implementations, subclasses can choose to extend. Hook method is usually an empty implementation.

1.3 Template Method Patterns - Advantages and Disadvantages

  • Advantages: encapsulation of immutable parts, expansion of variable parts, high code reuse.
  • Disadvantage: The parent abstracts the operation flow, while the child implements the specific operation steps. The code is not readable.

1.4 Template Method Patterns - Applicable Scenarios

  • Important and complex algorithms. Core algorithms can be designed as template methods
  • Multiple subclasses have similar operation steps and the same process, such as sending http requests, etc.
  • Template pattern is a frequently used pattern in refactoring.

2. Template Method Patterns - Application Examples

Let's assume a soft-fitting scene of a car. It takes three steps to assemble a car. It's a fixed process to install a skylight, a hologram and a sound. But different brands of audio can be installed.

Class 2.1 Graphs

2.2 Template abstract class

Abstract template class, define template method and step method:

  • constructCar: Template method, using final modification to prevent subclass tampering
  • buile*: Step method, defined as abstract method, is implemented by subclasses.
  • isBuildHologram: The hook method, which is subclassed to determine whether a holographic image needs to be installed.
public abstract class AbsCarProducer {

    // Assembling Standard Vehicle Types
    public final void constructCar(){
        System.out.println("Step 1:");
        this.buildSunroof();

        System.out.println("Step 2:");
        this.buildHologram();

        System.out.println("Step 3:");
        this.buildSound();

    }

    // Installation of panoramic skylights
    protected abstract void buildSunroof();

    // Installation of holograms
    protected abstract void buildHologram();

    // Install sound
    protected abstract void buildSound();
    
    // Whether to install hologram image, default installation
    boolean isBuildHologram(){
        return true;
    }
}

2.3 BenzProducer

  • Implementation of each step method
  • No overwriting hook method, default installation of holographic images
public class BenzProducer extends AbsCarProducer {
    @Override
    void buildSunroof() {
        System.out.println("\t Mercedes-Benz-Start installing sound");
    }

    @Override
    void buildHologram() {
        System.out.println("\t Mercedes-Benz-Start installing skylights");
    }

    @Override
    void buildSound() {
        System.out.println("\t Mercedes-Benz-Start installing sound");
    }
}

2.4 Mercedes-Benz Implementation Class-BMWProducer

  • Implementation of each step method
  • Rewrite hook method without installing holographic image
public class BMWProducer extends AbsCarProducer {
    @Override
    void buildSunroof() {
        System.out.println("\t bmw-Start installing sound");
    }

    @Override
    void buildHologram() {
        System.out.println("\t bmw-Start installing skylights");
    }

    @Override
    void buildSound() {
        System.out.println("\t bmw-Start installing sound");
    }

}

2.3 Test Class

The abstract class exposes only the constructCar() method to the outside world, and does not run the specific step method that calls it.

    @Test
    public void test_benz(){
        AbsCarProducer benzProducer = new BenzProducer();
        benzProducer.constructCar();

        System.out.println("\n********************************\n");
        AbsCarProducer bmwProducer = new BMWProducer();
        bmwProducer.constructCar();
    }

2.4 Test Output

  • Mercedes-Benz automobiles are assembled in three steps according to the template method.
  • BMW, according to the template method, has only two-step assembly.
Step 1:
	Mercedes-Benz - Start installing stereos
 Step 2:
	Mercedes-Benz - Start installing skylights
 Step 3:
	Mercedes-Benz - Start installing stereos

********************************

Step 1:
	BMW Cars - Start Installing Audio
 Step 3:
	BMW Cars - Start Installing Audio

Tags: Java

Posted on Tue, 27 Aug 2019 02:32:10 -0700 by Renich