Recently, we have seen the shadows of design patterns in many occasions. We have been investing in algorithms and data structures for a long time. It is very important to find the design patterns. Sometimes code maintenance, reuse, and scalability are better than pure algorithms. So I picked up Daniel's book "big talk Design Patterns" and referred to the blogs of various big cows on the Internet to start my design patterns journey.
Today, we will introduce the template method mode.
Concept:
Template Method (TemplateMethod): defines the algorithm skeleton in an operation, and delays some specific unique steps to the subclass. The template method is a subclass that can redefine the specific steps of some algorithms without changing the overall structure of the algorithm.
Advantages:
For the parent class, code reuse is implemented and a unified template is provided;
For the base class, avoid code duplication and improve the readability of the program.
The parent class contains abstract methods or excuses. It provides different implementations in sub-classes and completes different tasks of their objects through unified operations.
Sample Code:
Package Pattern;/** template class */abstract class TemplateClass {public abstract void Operation (); public void Method () {Operation ();}} /** Specific class 1 */class ConcreteClassOne extends TemplateClass {public void Operation () {System. out. println ("ConcreteClassOne: 1! ") ;}}/** Specific class 2 */class ConcreteClassTwo extends TemplateClass {public void Operation () {System. out. println (" ConcreteClassTwo perform Operation 2! ") ;}} Public class Pattern {public static void main (String [] args) {try {TemplateClass tempClass = new ConcreteClassOne (); tempClass. method (); tempClass = new ConcreteClassTwo (); tempClass. method ();} catch (Exception e) {System. out. println ("Java exception occurred! ");}}}