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

策略模式

序言

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

.

理解

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

源码

strategy.h

/// 策略
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

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

.
使用的地方

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会根据其拥有的策略进行运算。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

溪渣渣_梁世华

打赏?我甚至没有任何收费的章节

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值