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
相关推荐
曼巴UE55 小时前
UE5 音效系统
c++·游戏·ue5·虚幻·音效
无影无踪的青蛙5 小时前
[C++] list双向链表使用方法
c++·链表·list
tkevinjd6 小时前
C++中线程库的基本操作
开发语言·c++
CodeWithMe7 小时前
【C/C++】不同防止头文件重复包含的措施
c语言·开发语言·c++
Fre丸子_7 小时前
C++定长内存块的实现
c++
子豪-中国机器人7 小时前
C++ 信息学奥赛总复习题答案解析
开发语言·c++·算法
弥彦_7 小时前
牛客round95D
c++·算法
oioihoii7 小时前
C++11列表初始化:从入门到精通
java·开发语言·c++
tomato097 小时前
2025 年中国大学生程序设计竞赛全国邀请赛(郑州)暨第七届CCPC河南省大学生程序设计竞赛(补题)
c++
whoarethenext7 小时前
使用 C++/OpenCV 创建动态流星雨特效 (实时动画)
开发语言·c++·opencv