This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging

What is a Template Method pattern?

concept

The Template Method pattern is a behavioral pattern whose name may sound a little confusing. The template method pattern is defined in an abstract class to define a non-abstract method, in the non-abstract method defines how to call the abstract method, and these abstract method implementation is left to the subclass to complete, equivalent to the parent class defined framework, the subclass is responsible for the implementation of the framework content.

The template method pattern provides a specification for how we can use abstract classes and define both non-abstract and abstract methods in an object-oriented language.

There are also many such examples in real life, like a computer, the computer motherboard has been fixed to what things, CPU, hard disk, memory, which we can assemble themselves; As well as painting, it is generally to draw a basic frame first, and the remaining details and colors may be different for different people to draw.

advantages

  1. It conforms to the principle of openness and closure. To realize different functions, we only need to realize different subclasses, which improves the expansibility of the system.
  2. The parent class extracts the reused code and improves the reuse and maintainability of the code.

disadvantages

  1. Improved coupling between classes. Since it is implemented using inheritance, when an abstract class adds an abstract method, all subclasses must also add an abstract method.
  2. Makes the code harder to read. This is a reverse control structure. In general, the subclass calls the methods in the superclass, but here the superclass calls the methods in the subclass, which makes our design more abstract and harder to read.

All design patterns work best when used in the right context, but enforcing them is counterproductive.

The principle of

“+” means compliance, and “-” means noncompliance or irrelevant

The principle of Open the closed Single responsibility Di milt Replacement on the Richter scale Dependency inversion Interface segregation Synthesis of reuse
+ + + +

Applicable scenario

  1. Multiple subclasses have the same method, and the logic is basically the same.
  2. The basic logic/main architecture of a method is defined, but there are areas where the approach changes.

How to implement

To implement the template method pattern, you need two things:

  1. Template methods: Non-abstract methods in abstract classes that define the basic logical skeleton, the order in which the basic methods are called, and the processing operations.
  2. Basic methods: Abstract methods: declared in abstract classes and implemented by subclasses. Non-abstract methods: implemented in abstract classes, inherited by subclasses. Hook method: a method that is implemented in an abstract class and may not be implemented in subclasses.

The class diagram

Here is a class diagram of the template method pattern

The order in which the other methods are called is defined in TemplateMethod.

example

We all often go to drink milk tea, so on a hot day there is nothing more comfortable than drinking a cup of ice cold milk tea, if there is, it must be cold coke.

Make milk tea generally has a fixed step, add milk tea powder, add water, add sugar & seasoning, shake, add ice, package, this is a template, here the steps are unchanged, some are based on the requirements of the guests, we go to buy milk tea can be ordered a few minutes of sugar, less ice more ice.

The class diagram

code

Milk tea abstract class: Defines template methods, abstract methods, and non-abstract methods

/** * @author xuxiaobai */ abstract class MilkyTea{final */ final void process(){ addTeaPowderWithMilk(); addSugarAndCondiment(); addWrite(); shake(); addIce(); pack(); } /** * add teaosaap powder */ abstract void addteaosaap with milk (); /** * Add syrup and condiment */ abstract void addSugarAndCondiment(); /** * add water */ void addWrite(){system.out.println (" add water "); } void shake(){system.out.println (" shake "); } abstract void addIce(); Void pack(){system.out.println (" seal "); System. The out. Println (" bag "); System. The out. Println (" finished "); }}Copy the code

Sugar free and ice green milk tea: Achieving abstract methods

/ * * * sugar-free ice green tea * * @ author xuxiaobai * / public class NoSugarManyIceGreetMilkyTea extends MilkyTea {@ Override void Addteaosderwithmilk () {system.out.println (" add teaosderwithmilk "); } @override void addSugarAndCondiment() {system.out.println (" no sugar "); } @override void addIce() {system.out.println (" add half a cup of ice "); }}Copy the code

The test class:

/** ** @author xuxiaobai */ public class TemplateMethodTest {public static void main(String[] args) MilkyTea milkyTea=new NoSugarManyIceGreetMilkyTea(); Println ("-- sugar-free green milk tea making process --"); // Start making system.out.println ("-- sugar-free green milk tea making process --"); milkyTea.process(); /** * Results: * -- Sugar free and Iced green milk tea making process -- * Add green tea powder & milk * No sugar * Add water * Shake hard * Add half cup ice * Seal * Bag * Finished */}}Copy the code

Here simply write a sugar-free green milk tea class, many of the methods here are directly used in the abstract class, and then realize the class to achieve, you probably experience the use of template methods can be.

conclusion

The template method pattern provides guidance on the reverse control structure, defining how methods in an abstract class interact with methods in the implementation class. In fact, it is not necessary to specifically remember this design pattern, as long as you know that in abstract classes, non-abstract methods can use abstract methods, and abstract methods need subclasses to implement, it is ok, to a specific case, when doing code optimization when the template method pattern will naturally be used.

\