This series mainly records what the design pattern intends to be, what issues it wants to solve, and when it can be used; how it solves it, master its structure diagram, remember its key code; be able to think of at least two of its application instances, one in life and one in software; What are the advantages and disadvantages of this model, and what use scenarios are there, what should I pay attention to when using it.
Respect the author. For reposted, please indicate the Blog of Xiaoyang.Http://blog.csdn.net/hacke2
14. template method mode
Intention: Defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The Template Method allows the subclass to redefine some specific steps of the Algorithm without changing the structure of an algorithm.
Main Solution: Some methods are common, but this method is rewritten in every subclass.
When to use: There are some common methods
Solution: Abstract these general algorithms
Structure chart:
Key code: Implemented in the abstract class. Other steps are implemented in the subclass.
Application Instance: 1. When building a house, the foundation, cabling, and water pipes are the same. Only after the building is in the later stage can there be a gap between the closet and the fence. 2. It is difficult for the Bodhisattva to set up 81 in the Travel Notes to the west, this is a top-level logical skeleton. 3. Support for Hibernate in Spirng. It encapsulates Some preset methods, such as starting transactions, obtaining sessions, and closing sessions, the programmer can save the code without repeating the code that has already been standardized by dropping an entity.
Advantages: 1. encapsulate unchanged parts, expand variable parts 2. Extract Public Code to facilitate maintenance 3. behavior is controlled by the parent class, and sub-classes are implemented
Disadvantages: Each different implementation requires a subclass to implement, resulting in an increase in the number of classes, making the system larger
Use Cases: 1. There are multiple sub-classes that share the same logic. 2. important and complex methods can be considered as template methods.
Notes: To prevent malicious operations, the final keyword is usually added to the template method.