C++设计模式---策略模式

1、介绍

        策略模式(Strategy Pattern)是一种行为设计模式,它使你能在运行时改变对象的内部算法。策略模式定义了一系列的算法,并将每一个算法封装起来,使它们可以互相替换。策略模式使得算法可以独立于使用它的客户端变化。

        在C++中实现策略模式,通常会有一个策略接口(或抽象类),以及多个实现该接口的类(即策略);然后有一个上下文(Context)类,它使用策略接口,并在运行时注入(或设置)所需的策略

在C++中实现策略模式,由下面几部分组成:

        (1)抽象策略角色(strategy):抽象策略类。

        (2)具体策略角色(concrete strategy):封装了相关的算法和行为。

        (3)环境角色(context):持有一个策略类的引用,最终给客户端调用。

2、示例

实现0、1、2三种模式,打印三种模式下的内容。

头文件:

# ifndef _STRATEGY_H_
# define _STRATEGY_H_

// 使用枚举声明策略的种类
typedef enum Strategy_type {
    Strategy_type_0 = 0,
    Strategy_type_1,
    Strategy_type_2
}TYPE_MODE;

// 策略接口类【抽象类】
class Strategy {
public:
    virtual void Strategy_print() = 0;
};

// 具体的策略类
class Strategy_0:public Strategy {
public:
    void Strategy_print() {
        std::cout << "this is 000000" << std::endl;
    }
};

class Strategy_1:public Strategy {
public:
    void Strategy_print() {
        std::cout << "this is 111111" << std::endl;
    }
};

class Strategy_2 :public Strategy {
public:
    void Strategy_print() {
        std::cout << "this is 222222" << std::endl;
    }
};

class Context {
public:
    Strategy* sssttt;
    Context(TYPE_MODE mode) {
        switch (mode) {
            case Strategy_type_0:
                sssttt = new Strategy_0();
                break;
            case Strategy_type_1:
                sssttt = new Strategy_1();
                break;
            case Strategy_type_2:
                sssttt = new Strategy_2();
                break;
            default:
                sssttt = nullptr;
        }
    }

    ~Context() {
        if (nullptr != sssttt) {
            delete sssttt;
            sssttt = nullptr;
        }
    }
};

# endif

cpp文件:

#include <iostream>
#include "celue-moshi.h"

int main(int argc, char** argv) {
    Context* context_0 = new Context(Strategy_type_0);
    Context* context_1 = new Context(Strategy_type_1);
    Context* context_2 = new Context(Strategy_type_2);

    context_0->sssttt->Strategy_print();
    context_1->sssttt->Strategy_print();
    context_2->sssttt->Strategy_print();

    if (nullptr != context_0) {
        delete context_0;
        context_0 = nullptr;
    }

    if (nullptr != context_1) {
        delete context_1;
        context_1 = nullptr;
    }

    if (nullptr != context_2) {
        delete context_2;
        context_2 = nullptr;
    }

    return 0;
}

结果:

this is 000000
this is 111111
this is 222222

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值