Design Mode learning notes-Strategy Mode
Definition:
Policy patterns define a series of algorithms, encapsulate each algorithm, and make them replaceable. The rule mode allows algorithms to change independently of customers who use it.
When we use some features, there are sometimes many implementation methods or multiple results, but they all use the same method, that is, calling the interface. This is the policy mode.
Example:
// Design mode Demo. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
# Include
Using namespace std; // traffic policy base class, which defines a policy interface class TrafficStrategyBase {public: virtual void goHome () = 0 ;}; // The walking policy class implements stragety: public TrafficStrategyBase {public: void goHome () override {cout <"go home on foot" <
GoHome (); // use the Walking strategy = new inclustragety (); strategy-> goHome (); system ("pause"); return 0 ;}
Result: go home by car
Go home on foot
The above is the simplest rule mode, which is actually a C ++ polymorphism. The parent class pointer is used to call the subclass function without having to know what the subclass is. However, this example has many drawbacks, and the client needs to know that various modes are not conducive to modification.
The following is a simple optimization that combines the policy mode with the simple factory mode:
// Design mode Demo. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
# Include
Using namespace std; // traffic policy base class, which defines a policy interface class TrafficStrategyBase {public: virtual void goHome () = 0 ;}; // The walking policy class implements stragety: public TrafficStrategyBase {public: void goHome () override {cout <"go home on foot" <
CreateStrategy (Drive)-> goHome (); // use the walking policy to go home factory-> CreateStrategy (Walk)-> goHome (); system ("pause"); return 0 ;}
Here, the client has nothing to do with the various policies themselves. We only need to modify the parameters of the simple factory to create the corresponding policies and perform operations using the corresponding methods. The parameter can be changed to the string read in the configuration file, which is more conducive to expansion.
Furthermore, we can use the factory method mode + reflection, without modifying the client code to change the usage policy. However, C ++ does not have a reflection mechanism. Although there are methods to implement the reflection mechanism, I will not do it for the time being... You have the opportunity to fill in.