Design Mode 2-Policy Mode

Source: Internet
Author: User

The factory mode creates different objects for different types. When the required objects are not changed, but the operations and algorithms on them are not the same, the policy mode can be used.

Create different algorithm classes in Rule mode, return a pointer to a base class algorithm object, and perform related calculations or operations on it.

 

Instance code

Strategy. H Content

 1 #ifndef Strategy_H_H 2 #define Strategy_H_H 3  4 #include <iostream> 5 using namespace std; 6  7 class Oper 8 { 9 public:10     Oper() {}11     virtual int getResult(int a, int b) = 0;12     virtual ~ Oper() {}13 };14 15 class OperAdd : public Oper16 {17 public:18     virtual int getResult(int a, int b) { return a+b; }19 };20 21 class OperSub : public Oper22 {23 public:24     virtual int getResult(int a, int b) { return a-b; }25 };26 27 class Strategy28 {29 public:30     Strategy(int a0, int b0) : a(a0), b(b0), oper(NULL) {}31     int getResult(){32         return oper->getResult(a, b);33     }34     void setOper(Oper *oper0){35         oper = oper0;36     }37 private:38     int a, b;39     Oper *oper;40 };41 42 void StrategyTest()43 {44     Strategy *strategy = new Strategy(4, 3);45     strategy->setOper( new OperAdd() );46     cout << strategy->getResult() << endl;47     strategy->setOper( new OperSub() );48     cout << strategy->getResult() << endl;49     delete strategy;50 }51 52 #endif

The running result is obvious.

Of course, memory leakage and other issues are not considered here, so you need to pay attention to them during use. To optimize it, you can add reference counting, smart pointer, and other mechanisms.

Design Mode 2-Policy Mode

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.