策略模式

#include <iostream>
using namespace std; 

//策略基类
class COperation
{
protected:
    int m_nFirst;
    int m_nSecond;
public:
    virtual ~COperation(){}
    virtual double GetResult() = 0;
};

//策略具体类—加法类
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 SubOperation : public COperation
{
public:
    SubOperation(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(COperation* temp) :op(temp){}
    void setStrategy(COperation* temp){
        op = temp;
    }
    double GetResult(){
        if (op != nullptr){
            return op->GetResult();
        }
    }
};

//客户端
int main()
{
    int a, b;
    char ch;
    cout << "输入运算数:a b \n";
    cin >> a >> b;
    cout << "输入运算符:\n";
    cin >> ch;
    Context* p = nullptr;
    COperation* op = nullptr;
    switch (ch)
    {
    case '+':
        op = new AddOperation(a, b);
        p = new Context(op);
        cout << p->GetResult()<< endl;      
        break;
    case '-':
        break;
    default:
        break;
    }
    delete op;
    delete p;
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值