QtC++ 设计模式(四)——策略模式

策略模式

序言

还是参考的菜鸟教程,会C++的还是看C++的方式来得舒服。

.

理解

使用符合UML规范的便于理解和回忆,接口其实就是普通的基类

.

源码

strategy.h

cpp 复制代码
/// 策略
class Strategy
{
public:
    virtual ~Strategy();
    
    /**
     * @brief 计算
     * @param num1 计算数值
     * @param num2 被计算数值
     * @return 
     */
    virtual int operation(const int& num1, const int& num2) = 0;
};

/// 加策略
class AddOperation : public Strategy
{
public:
	/**
     * @brief 加计算
     * @param num1 计算数值
     * @param num2 被计算数值
     * @return 
     */
    int operation(const int &num1, const int &num2) override;
};

/// 减策略
class SubtractOperation : public Strategy
{
public:
	/**
     * @brief 减计算
     * @param num1 计算数值
     * @param num2 被计算数值
     * @return 
     */
    int operation(const int &num1, const int &num2) override;
};

/// 上下文
class Context
{
public:
    /**
     * @brief 构造一个策略的上下文
     * @param strategy 策略对象
     */
    explicit Context(Strategy *strategy);
    ~Context();

	/**
     * @brief 计算
     * @param num1 计算数值
     * @param num2 被计算数值
     * @return 
     */
    int operation(const int &num1, const int &num2);

private:
	/// 所拥有的策略
    Strategy *strategy = nullptr;
};

.

strategy.cpp

cpp 复制代码
Strategy::~Strategy()
{

}

int AddOperation::operation(const int &num1, const int &num2)
{
    return num1 + num2;
}

int SubtractOperation::operation(const int &num1, const int &num2)
{
    return num1 - num2;
}

Context::Context(Strategy *strategy)
    : strategy(strategy)
{

}

Context::~Context()
{
    if (strategy)
        delete strategy;
}

int Context::operation(const int &num1, const int &num2)
{
    if (strategy)
    {
        return strategy->operation(num1, num2);
    }
    return INT_MIN;
}

.

使用的地方

cpp 复制代码
std::shared_ptr< Context > context(new Context(new AddOperation));
std::cout << context->operation(10, 5) << std::endl;

context.reset(new Context(new SubtractOperation));
std::cout << context->operation(10, 5) << std::endl;

不同策略则生成不同的对象给Context,Context会根据其拥有的策略进行运算。

相关推荐
QuantumStack2 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6732 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
缘来是庄2 小时前
设计模式之访问者模式
java·设计模式·访问者模式
whoarethenext2 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
Jay_5153 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
xiaolang_8616_wjl4 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
FrostedLotus·霜莲5 小时前
C++主流编辑器特点比较
开发语言·c++·编辑器
hqxstudying5 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
花好月圆春祺夏安6 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
fie88896 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式