Define the algorithm family, encapsulate them separately, so that they can be replaced, so that the algorithm changes do not affect the user. The policy mode is basically the same as the simple Factory mode, but the simple factory can only solve the object creation problem, and the policy mode should be used for the frequently changing algorithm.
Code implementation:
#include <iostream>using namespace std;//strategy base classes Class Coperation{public:int M_nfirst;int m_nsecond;virtual double Gerresult () {double Dresult=0;return dresult;}};/ /Policy Specific class-Additive class class Addoperation:public coperation{public:addoperation (int a,int b) {m_nfirst=a;m_nsecond=b;} Virtual Double GetResult () {return m_nfirst+m_nsecond;}}; Class context{private:coperation* Op;public:context (char cType) {switch (cType) {case ' + ': op=new addoperation (3,8); Break;default:op=new addoperation (); break;}} Double GetResult () {return op->gerresult ();}};/ /client int main () {int A,b;char c;cout<< "input operand, middle space interval:" <<endl;cin>>a>>b; context* test=new Context (' + '); Cout<<test->gerresult () <<endl;return 0;}
C + + policy mode