Learning C # design patterns series notes (1) strategy patterns,
I. References
1. Head First Design Patterns (Chinese name: deep dive into Design Patterns)
2. Wikipedia, policy model, https://zh.wikipedia.org/wiki/%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F
Ii. Strategy Pattern)
Encapsulate the same type of algorithms to form an algorithm family. Only the same interface is provided to the outside world. The algorithms in the same algorithm family can be replaced with each other. When the outside world is used, there is no difference, that is, algorithms in the algorithm family exist independently of users.
Students students and Teacher can go to School by Bus, Subway, and Car.
So there is the first case: Student has goToSchoolByBus, goToSchoolBySubway, goToSchoolByCar function, Teacher also has goToSchoolByBus, goToSchoolBySubway, goToSchoolByCar function, UML. However, this is too redundant. Here, Redundancy refers to: "transport mode" is a shared part. Student and Teacher can both sit on Bus, Subway, and Car. In addition, it is not flexible. If you suddenly have other requirements, such as walking to school, Student and Teacher will be modified separately, which is time-consuming and laborious, there may also be side effects (such as unexpected bugs). Therefore, you need to extract the parts that may change and make these parts into an algorithm family.
Therefore, to improve the above situation, Student and Teacher both have the goToSchool function and hold an IWay interface reference, the algorithms related to Bus, Subway, and Car are encapsulated in the IWay algorithm family. In this Way, unified management is convenient, and unified calling is convenient. When you need to add an algorithm, you only need to modify the Way without affecting the original Student and Teacher. Moreover, it is easy to reuse. In this case, studentA has eye disease and needs the help of the guide Dog dogA to go to school. At this time, Dog also has the goToSchool function, it also holds an IWay interface reference. UML:
- When can I consider using the Policy mode?
There are changed parts in the code, and this part can be extracted (try to use "interface-oriented", which facilitates decoupling)
- Specific C # implementation
The code for the design pattern (C #) is all put on git: https://github.com/MGKING3/DesignPatternsUseCSharp
I use VS2015, which is a whole project. It can be downloaded and updated from time to time. The CS file in this mode is TestStrategyPattern.
1. encapsulation principles
2. Multi-Purpose Combination (has-a) and less inheritance (is-)
3. Try to "interface-oriented"