C + + policy mode

Source: Internet
Author: User
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

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.