Overview
Changes have always been an eternal topic of software design. In XP programming, we advocate embracing changes and actively coping with them. How can we better grasp the change point and respond to the change? How can we improve code reuse? By learning the Template Method mode, you should have a new understanding.
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 certain steps of an algorithm without changing the structure of an algorithm. [-GOF design patterns]
Structure chart
Figure 1 Structure of the Template Method mode
Examples in life
The template method defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. Architects use the template method when developing new projects. A typical plan includes some floor plans, each of which reflects different parts. In a plan, the foundation, structure, water loading, and cabling are the same for each room. Different house styles are generated only when there is a difference in the later stage of the building.
Figure 2 use the Template Method mode of the building diagram as an Example
Example
Define a supermarket abstract class. Each supermarket inherits this abstract class to form our template mode. The example is shown below:
Code Design
Create ISuperMarket. cs First:
01 |
public interface ISuperMarket |
04 |
/// Activity start time |
06 |
/// <returns></returns> |
07 |
DateTime PreferencesStartTime(); |
12 |
/// <returns></returns> |
18 |
/// <returns></returns> |
24 |
/// <returns></returns> |