【设计模式】策略模式

概念

行为模式


类图


代码

cpp 复制代码
#include <iostream>

using namespace std;

class Strategy {
public:
    ~Strategy() = default;
    virtual int Execute(int a, int b) = 0;
};

class ConcreteStrategyAdd : public Strategy {
    int Execute(int a, int b) override {
        return a + b;
    }
};

class ConcreteStrategySubtract : public Strategy {
    int Execute(int a, int b) override {
        return a - b;
    }
};

class ConcreteStrategyMultiply : public Strategy {
    int Execute(int a, int b) override {
        return a * b;
    }
};

class Context {
public:
    void SetStrategy(Strategy* s) {
        strategy = s;
    }

    int ExecuteStrategy(int a, int b) {
        return strategy->Execute(a, b);
    }

private:
    Strategy* strategy;
};

int main(int argc, char *argv[]) {
    auto context = new Context();
    int a = 10, b = 25;

    string action = "add";
    if (action == "add") {
        context->SetStrategy(new ConcreteStrategyAdd());
    } else if (action == "subtraction") {
        context->SetStrategy(new ConcreteStrategySubtract());
    } else if (action == "multiplication") {
        context->SetStrategy(new ConcreteStrategyMultiply());
    } else {
        cout << "Wops! Error Action." << endl;
        return -1;
    }

    cout << context->ExecuteStrategy(a, b) << endl;

    delete context;

    return 0;
}
相关推荐
Zane19942 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫3 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19943 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19944 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..5 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1505 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)6 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki6 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅666 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa6 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio