Home  >  Article  >  Java  >  Detailed explanation of java template method pattern (with examples)

Detailed explanation of java template method pattern (with examples)

不言
不言forward
2018-10-24 11:31:501832browse

This article brings you a detailed explanation of the Java template method pattern (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Template method pattern: Define an algorithm framework in operation, and defer some steps to subclasses, so that subclasses can redefine specific steps of the algorithm without changing the algorithm structure. .

Advantages: 1. Encapsulate the immutable part, extend the variable part, and encapsulate the algorithm considered immutable in the parent class implementation, while the variable part can continue to be expanded through inheritance.

2, the behavior is controlled by the parent class and implemented by the subclass.

A simple example of template approach
Define abstract interface

Detailed explanation of java template method pattern (with examples)

Two different implementations

Detailed explanation of java template method pattern (with examples)

Detailed explanation of java template method pattern (with examples)

Scenario Class

Detailed explanation of java template method pattern (with examples)

Result

Detailed explanation of java template method pattern (with examples)

Through the log, we can find that the call to this is exactly the call to the implemented subclass.

By modifying the logic of the commonMan implementation class, we can obtain different logical components.
After modification,

Detailed explanation of java template method pattern (with examples)

is called The business scenario class is still the same

Detailed explanation of java template method pattern (with examples)

Result

Detailed explanation of java template method pattern (with examples)

Passed result , we can also see that when the implementation of a subclass is modified, the parent class and other classes remain unchanged, and the business changes are realized.


The above is the detailed content of Detailed explanation of java template method pattern (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more