c++实现策略模式

一.策略模式简介

  策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。简单工厂模式是创建型模式,它的作用是创建对象。策略模式是行为型模式,作用是在许多行为中选择一种行为,关注的是行为的多样性。简单来说策略模式就是将多种行为方法封装成一种策略并统一做调用,调用的方法相同,具体策略执行的算法不同。下面以商场促销的应用为场景简要介绍策略模式的使用。并在最后和简单工厂进一步结合,做更好的封装,给用户层面提供更简单的操作。

二.单纯策略模式cpp代码实现

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

//策略基类
template <class mytype>
class strategy
{
public:
    strategy() = default;        //默认构造函数

    //定义纯虚函数,由子类继承
    virtual mytype getresult() const = 0;
    //赋值运算符=重载
    strategy<mytype>& operator=(const strategy<mytype>& strategy_t)
    {
        this->money_input = strategy_t.money_input;
    }
    mytype money_input;
private:
};

//打七折策略
template <class mytype>   //定义模板
class strategy_7discount :public strategy<mytype>
{
public:
    virtual mytype getresult()const
    {
        cout << "打七折策略" << endl;
        return this->money_input * 0.7;
    }
private:
};

//打八折策略
template <class mytype>   //定义模板
class strategy_8discount :public strategy<mytype>
{
public:
    virtual mytype getresult()const
    {
        cout << "打八折策略" << endl;
        return this->money_input * 0.8;
    }
private:
};

//满减策略
template <class mytype>   //定义模板
class strategy_oversub :public strategy<mytype>
{
public:
    virtual mytype getresult()const
    {
        cout << "满减策略" << endl;
        if (this->money_input > 200)return this->money_input - 50;
        else if (this->money_input > 100)return this->money_input - 20;
        return this->money_input;
    }
private:
};

//定义一个策略context
template <class mytype>   //定义模板
class context
{
public:
    strategy<mytype>* my_strategy;     //定义我的策略,也就是在context内部维护了策略的一个基类指针
    //context默认构造函数
    context(strategy<mytype>* strategy_t)
    {
        my_strategy = strategy_t;              //初始化context时传入具体的策略对象的指针
    }
    //上下文接口
    mytype context_interface()
    {
        return my_strategy->getresult();     //根据具体的策略对象,调用其算法的方法
    }
private:
};

int main(void)
{
    float result = 0;
    strategy_7discount<float>* strategy_7discount_t = new strategy_7discount<float>;   //1.new创建具体的策略算法对象
    strategy_7discount_t->money_input = 312;                                            //2.设置策略对象的入口参数
    context<float> my_context(strategy_7discount_t);                                    //3.创建context策略对象my_context并将策略算法对象指针作为入口参数传入
    result = my_context.context_interface();                                            //4.调用context策略的接口方法
    cout << "最终的价格是:" << result << endl;

    cout << "--------------------------------------------------------------" << endl;
    int res = 0;
    strategy_oversub<int>* strategy_oversub_t = new strategy_oversub<int>;
    strategy_oversub_t->money_input = 402;
    context<int> my_context1(strategy_oversub_t);
    res = my_context1.context_interface();
    cout << "最终的价格是:" << res << endl;
    
    return 0;
}

执行结果:

打七折策略
最终的价格是:218.4
--------------------------------------------------------------
满减策略
最终的价格是:352

三.策略模式+简单工厂模式cpp代码实现

  在之前代码的基础上增加一个工厂类cashcontext。然后在main中使用工厂来做策略调用。

//定义一个简单工厂,来选择使用哪个运算
template <class mytype>   //定义模板
class cashcontext
{
public:
    strategy<mytype>* strategy_t = NULL;
    context<mytype>* my_context = NULL;
    //默认构造函数
    cashcontext() = default;     
    //有参构造函数
    cashcontext(int choice, mytype money)
    {
        switch (choice)
        {
            case 1:     //七折策略
                strategy_t = new strategy_7discount<mytype>;   //1.new创建具体的策略算法对象
                break;
            case 2:     //八折策略
                strategy_t = new strategy_8discount<mytype>;   //1.new创建具体的策略算法对象
                break;
            case 3:     //满减策略
                strategy_t = new strategy_oversub<mytype>;   //1.new创建具体的策略算法对象
                break;
            default:
                cout << "输入参数有误,请重新输入" << endl;
                break;
        }
        strategy_t->money_input = money;          //设置入口参数
        my_context = new context<mytype>(strategy_t);   //创建context策略对象
    }
    //获取结果
    mytype get_result(void)
    {
        return my_context->context_interface();
    }
private:
};

int main(void)
{
    float result = 0;
    cashcontext<float> cashcontext_t(1, 452);   //1表示七折策略
    result = cashcontext_t.get_result();
    cout << "最终的价格是:" << result << endl;
    
    return 0;
}

执行结果:

打七折策略
最终的价格是:316.4

四.总结

  简单工厂模式和策略模式的最大区别是:简单工厂模式注重返回的子类对象。策略模式注重执行策略方法的调用。简单工厂模式和策略模式的配合使用会使代码结构更加清晰。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++策略模式是一种行为型设计模式,它可以在运行时根据需要选择不同的算法或策略来完成特定的任务,而不需要改变客户端代码。 在策略模式中,首先定义一个抽象策略基类,该基类声明了一个执行策略的纯虚函数。然后,针对不同的具体策略,派生出不同的子类,并实现各自的策略算法。 客户端代码可以通过持有策略基类的指针或引用来使用策略,而不需要知道具体使用的是哪个策略。在运行时,可以动态地将不同的具体策略对象传递给客户端,从而实现不同策略的切换。 以下是一个简单的示例: ```cpp // 抽象策略基类 class Strategy { public: virtual void execute() = 0; }; // 具体策略类1 class ConcreteStrategy1 : public Strategy { public: void execute() override { // 实现策略1的算法逻辑 } }; // 具体策略类2 class ConcreteStrategy2 : public Strategy { public: void execute() override { // 实现策略2的算法逻辑 } }; // 客户端类 class Client { private: Strategy* strategy; // 持有策略基类的指针 public: void setStrategy(Strategy* newStrategy) { strategy = newStrategy; } void executeStrategy() { strategy->execute(); // 调用策略的执行函数 } }; // 使用示例 int main() { Client client; ConcreteStrategy1 strategy1; ConcreteStrategy2 strategy2; client.setStrategy(&strategy1); client.executeStrategy(); // 调用策略1的算法逻辑 client.setStrategy(&strategy2); client.executeStrategy(); // 调用策略2的算法逻辑 return 0; } ``` 通过使用策略模式,可以实现算法的灵活切换和扩展。客户端代码只需关注使用策略的接口,而策略的具体实现则可以在运行时动态地选择和切换。这样可以提高代码的可维护性和可扩展性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

tutu-hu

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值