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