separating the definition and use of the algorithm is the problem that the strategy pattern solves .
The main purpose of the strategy pattern is to separate the definition and use of the algorithm, that is, to separate the behavior of the algorithm from the environment .
As in the discount class, the class is a concrete algorithm class, which only the behavior of the algorithm, that is, the behavior of calculating prices. In the Environment class, the Environment class defines the environment in which the algorithm is used.
The policy pattern provides a way to replace an inheritance relationship. The use of algorithms is mixed with the algorithm itself, and does not conform to the "single responsibility Principle", if the logic of deciding which algorithm to use is mixed with the algorithm itself, it is impossible to evolve independently, and using inheritance cannot implement the dynamic switching of an algorithm or behavior while the program is running.
Scenarios for which the policy mode applies:
(1) An object has a lot of behavior, if not the appropriate pattern, these behaviors have to use multiple conditional selection statements to implement. In this case, using the policy mode, transfer these behaviors to the corresponding specific policy class, you can avoid the use of difficult to maintain multiple conditional selection statements.
(2) Do not want the client to know the complex, algorithm-related data structure, in the specific policy class encapsulation algorithm and related data structure, can improve the confidentiality and security of the algorithm.
Above from my esteemed teacher Liu Wei's blog: http://blog.csdn.net/lovelion/article/details/7819266
Thank you teacher!
Strategy Mode Learning