C + + Design mode--policy mode (strategy)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.