【C++代码】设计模式之策略模式

// =================================================================================
class Strategy
{
public:
    Strategy() {};
    virtual ~Strategy() {};
    virtual void getCurrentStrategy() = 0;   // 作为接口
};

// 派生类,策略1
class Strategy1 : public Strategy
{
public:
    Strategy1() {};
    ~Strategy1() {};
    virtual void getCurrentStrategy(){ cout << "当前使用的策略是Strategy1" << endl; }
};

// 派生类,策略2
class Strategy2 : public Strategy
{
public:
    Strategy2() {};
    ~Strategy2() {};
    virtual void getCurrentStrategy(){ cout << "当前使用的策略是Strategy2" << endl; }
};

// 派生类,策略3
class Strategy3 : public Strategy
{
public:
    Strategy3() {};
    ~Strategy3() {};
    virtual void getCurrentStrategy(){ cout << "当前使用的策略是Strategy3" << endl; }
};


// =================================================================================
class Context
{
private:
    Strategy *pStrategy = nullptr;
public:
    Context(Strategy *pStrategyArg) : pStrategy(pStrategyArg){}
    void ContextInterface(){
        pStrategy->getCurrentStrategy();
    }
};

// 客户端代码=================================================================================
void client() {
    Strategy *pStrategy1 = new Strategy1();
    Context *pContext1 = new Context(pStrategy1);
    pContext1->ContextInterface();
    if (pStrategy1) delete pStrategy1;
    if (pContext1) delete pContext1;

    Strategy *pStrategy2 = new Strategy2();
    Context *pContext2 = new Context(pStrategy2);
    pContext2->ContextInterface();
    if (pStrategy2) delete pStrategy2;
    if (pContext2) delete pContext2;

    Strategy *pStrategy3 = new Strategy3();       
    Context *pContext3 = new Context(pStrategy3);        
    pContext3->ContextInterface();       
    if (pStrategy3) delete pStrategy3;        
    if (pContext3) delete pContext3;
}

int main() {
    client();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值