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

1、介绍

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

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

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

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

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

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

2、示例

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

头文件:

cpp 复制代码
# 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文件:

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;
}

结果:

cpp 复制代码
this is 000000
this is 111111
this is 222222
相关推荐
找了一圈尾巴5 分钟前
设计模式-组合模式、模板模式
设计模式·组合模式
qing_0406031 小时前
数据结构——二叉搜索树
数据结构·c++·二叉树·二叉搜索树
Ljw...2 小时前
DeepSeek+Kimi生成高质量PPT
数据库·c++·powerpoint·ppt·deepseek
敲上瘾2 小时前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
float_六七2 小时前
Java——单例类设计模式
java·单例模式·设计模式
禁默2 小时前
C++之旅-C++11的深度剖析(1)
开发语言·c++
老菜鸟的每一天2 小时前
创建型模式-Prototype 模式(原型模式)
设计模式·原型模式
张有志_2 小时前
STL容器终极解剖:C++ vector源码级实现指南 | 从内存分配到异常安全的全流程避坑
c语言·c++·算法·开源·visual studio
挨代码2 小时前
UE_C++ —— Delegates
c++·ue
熊出没3 小时前
解锁策略模式:Java 实战与应用全景解析
策略模式