设计模式之策略模式(Strategy)

策略模式是指定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。使得算法可独立于使用它的客户而变化。也就是说这些算法所完成的功能一样,对外的接口一样,只是各自实现上存在差异。用策略模式来封装算法,效果比较好

#include <iostream>

using namespace std;

//抽象接口
class Algorithm
{
public:
    virtual void replace() = 0;
};

//算法1
class Algorithm1 : public Algorithm
{
public:
    void replace()
    {
        cout << "this is Algorithm1" << endl;
    }
};

//算法2
class Algorithm2 : public Algorithm
{
public:
    void replace()
    {
        cout << "this is Algorithm2" << endl;
    }
};

//算法3
class Algorithm3 : public Algorithm
{
public:
    void replace()
    {
        cout << "this is Algorithm3" << endl;
    }
};

enum AlgorithmFlag
{
    A1,
    A2,
    A3
};

//计算
class Compute
{
public:
    Compute(enum AlgorithmFlag flag)
    {
        if(flag == A1)
            _algorithm = new Algorithm1;
        else if(flag == A2)
            _algorithm = new Algorithm2;
        else if(flag == A3)
            _algorithm = new Algorithm3;
        else
            _algorithm = NULL;

    }
    ~Compute()
    {
        if(_algorithm)
            delete _algorithm;
    }

    void replace()
    {
        _algorithm->replace();
    }

private:
    Algorithm *_algorithm;
};



int main()
{
    Compute compute(A1);
    compute.replace();
    return 0;
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值