The policy pattern is a behavioral design pattern (behavioral pattern) that uses different algorithms (the relationship between algorithms is parallel, that is, they solve the same problem, but take different strategies, such as KMEANS,FCM between clusters) encapsulated in different classes , also known as the policy pattern, is used to organize different algorithms for solving the same problem, so that the client (and the context class below) can easily be called flexibly. Finally, the substitution and change of the algorithm can be done independently of the client.
Its UML class diagram relationships are as follows:
Class strategy{ Public:Virtual~Strategy(){}Virtual voidEXEC () =0;}; Class Strategya: Publicstrategy{ Public:void exec() {cout <<"Strategya::exec ()"<< Endl; }};class Strategyb: Publicstrategy{ Public:void exec() {cout <<"Strategyb::exec ()"<< Endl; }};class context{ Public:Explicit Context(strategy* strategy): _Strategy(strategy) {}voidSet_strategy (strategy* strategy) {_strategy = strategy;}voidEXEC () {_strategy->exec ();}Private: strategy* _strategy; };
Let's look at the client's invocation situation:
int main(int, char**){ StrategyA sa; StrategyB sb; Context ca(&sa); Context cb(&sb); ca.exec(); cb.exec(); "=========================" << endl; ca.set_strategy(&sb); cb.set_strategy(&sa); // 客户端,也即Context对象,可十分方便的切换切换自己的算法 ca.exec(); cb.exec(); return0;}
The result of the final operation is:
StrategyA::exec()StrategyB::exec()=========================StrategyB::exec()StrategyA::exec()
C + + Design mode--policy mode (strategy)