Design pattern-Template Method pattern

What is template pattern?

Generally, when writing programs, there are often many different business codes, some of which have different specific implementations, but there are still many logics or other implementations that are the same.
If we just copy and paste these common parts, then once we find a problem with these codes, we need to go back and check all the parts that use these codes.
The correct way to handle it is to extract the common parts of all codes, put these common parts into the same abstract class, declare different concrete methods as abstract methods, and let the subclasses implement their own details.
Insert image description here

give a chestnut

We want to print characters and strings, each of which is printed 5 times, but the special symbols at the beginning and end are different.
Then we should declare these three methods with different specific implementations, start, print, and end, as abstract methods in the template method, and let the subclasses implement their own detailed implementations.
Then these common parts: print the start symbol first, print the character/string 5 times, and finally print the end special character in the abstract parent class.
When the subclass inherits the parent class, there is no need to rewrite the implemented common method of the parent class.
In the Main function, we use the parent class to declare the subclass, so that when calling the subclass method, the methods implemented by the subclass itself are used, and the methods implemented by the parent class that have not been overridden by the subclass are used. Directly call methods already implemented by the parent class.

Insert image description here

Liskov Substitution Principle

This principle is very important in inheritance, so it must be understood and remembered.
The Liskov Substitution Principle (LSP): No matter which instance of the subclass is saved in a variable of the parent class type, the program will work normally.
LSP is not limited to template patterns, but is a general inheritance principle.

Class Hierarchy and Abstract Classes - Requirements of Parent Classes on Subclasses

Understanding from a subcategory perspective:

  • Methods defined in the parent class can be used in subclasses
  • New functions can be realized by adding methods in subclasses
  • Overriding the methods of the parent class in the subclass can change the behavior of the program

Understanding from the perspective of parent class:

  • Expect subclasses to implement abstract methods
  • Require subclasses to implement abstract methods

That is, subclasses have the responsibility to implement abstract methods declared in superclasses. This responsibility is called "subclass responsibility".

Guess you like

Origin blog.csdn.net/qq_23128065/article/details/90545004