Behavior mode-Rule Mode
Strategy Pattern: There may be multiple ways to complete a task. which method is most effective depends on the conditions, the policies selected under different conditions are also different. In this case, you need to make various judgments on the current situation in an environment and implement the branch structure in the program design, that is, in an environment class, different branches are used to determine which strategy to use. This design method encapsulates implementation policies and the current environment in a class is called hard encoding. Hard coding has the following Disadvantages: First, if the environment changes and requires conditional judgment, you need to modify the current environment class to add branches; second, in terms of real-time performance, the customer may be reluctant to Support Branch algorithms they do not need, because Branch judgment may lead to a certain delay. Furthermore, it is not difficult to understand the mixing of the implementation module and the environment status, it is also more difficult to maintain. For the above reasons, the policy mode can be used to solve the problem. The Strategy Mode is simple but effective. It encapsulates each policy into a specific class, and extracts the public interfaces of each policy into a policy interface to allow the environment class to interact with the policy interface. In this way, if you want to add a new policy method, you only need to add an implementation class of the policy interface, and the Environment class does not have to pay attention to which policy should be used, because in its view, all policy methods are the same. Mode code: bt _ rule mode. h:
1 # ifndef SP_H 2 # define SP_H 3 # include <iostream> 4 using namespace std; 5 6/* 7 abstract policy interface 8 */9 class Strategy10 {11 public: 12 virtual ~ Strategy () {} 13 virtual void Algorithm () = 0; 14}; 15 16/* 17 specific policy class 18 */19 class ConcreteStrategyA: public Strategy20 {21 public: 22 virtual void Algorithm () 23 {24 cout <"Use Policy A" <endl; 25} 26}; 27 class ConcreteStrategyB: public Strategy28 {29 public: 30 virtual void Algorithm () 31 {32 cout <"Use Policy B" <endl; 33} 34 }; 35 36/* 37 environment Context class 38 */39 class Context40 {41 public: 42 Context (Strategy * s): strategy (s) {}43 void Execute () 44 {45 strategy-> Algorithm (); 46} 47 48 private: 49 Strategy * strategy; 50}; 51 52 # endif // SP_H
Test Case. cpp:
1 # include "bt _ policy mode. h "2 3 int main () 4 {5 cout <" ***** rule mode test ***** "<endl; 6 Strategy * strategy = new ConcreteStrategyA; 7 Context * context = new Context (strategy); 8 context-> Execute (); 9 10 delete context; 11 delete strategy; 12 13 return 0; 14}