策略模式(C++)

#include <iostream>
#include <string>
using namespace std;

class math
{
public:
    math(){}
    virtual ~math(){}
    virtual void add()=0;
};

class ADD1 : public math
{
public:
    ADD1(){}
    virtual ~ADD1(){}
    void add()
    {
        cout<<"the first type of add"<<endl;
    }
};

class ADD2 : public math
{
public:
    ADD2(){}
    virtual ~ADD2(){}
    void add()
    {
        cout<<"the second type of add"<<endl;
    }
};

class calculate
{
public:
    calculate(){}
    ~calculate(){}
    void set_alg(math *p)
    {
        p_math=p;
    }
    void operation()
    {
        p_math->add();
    }

protected:
    math *p_math;
};

int main()
{
    calculate *p_cal=new calculate;
    math *p_add1=new ADD1;
    math *p_add2=new ADD2;
    
    p_cal->set_alg(p_add1);
    p_cal->operation();
    p_cal->set_alg(p_add2);
    p_cal->operation();

    delete p_add2;
    delete p_add1;
    delete p_cal;

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/tiandsp/p/2571314.html