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
相关推荐
派阿喵搞电子19 分钟前
在UI界面内修改了对象名,在#include “ui_mainwindow.h“没更新
c++·qt·ubuntu·ui
C++ 老炮儿的技术栈1 小时前
UDP 与 TCP 的区别是什么?
开发语言·c++·windows·算法·visual studio
mochensage3 小时前
CSP信奥赛C++常用系统函数汇总
c++·信奥
mochensage3 小时前
C++信息学竞赛中常用函数的一般用法
java·c++·算法
fpcc3 小时前
跟我学c++中级篇——多线程中的文件处理
c++
5:004 小时前
云备份项目
linux·开发语言·c++
乄夜5 小时前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
YYDS3145 小时前
C++动态规划-01背包
开发语言·c++·动态规划
wydaicls5 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
姜君竹6 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构