温馨提示×

如何在C++中实现策略模式

c++
小樊
81
2024-08-29 18:49:18
栏目: 编程语言

策略模式(Strategy Pattern)是一种行为设计模式,它使你能在运行时改变对象的行为

下面是一个简单的示例,展示了如何在C++中实现策略模式:

  1. 首先,定义一个策略接口:
#include<iostream>
#include<string>

// 策略接口
class Strategy {
public:
    virtual ~Strategy() = default;
    virtual void execute(const std::string& message) = 0;
};
  1. 然后,创建一些具体的策略类,实现上述接口:
// 具体策略A
class ConcreteStrategyA : public Strategy {
public:
    void execute(const std::string& message) override {
        std::cout << "Called ConcreteStrategyA with message: "<< message<< std::endl;
    }
};

// 具体策略B
class ConcreteStrategyB : public Strategy {
public:
    void execute(const std::string& message) override {
        std::cout << "Called ConcreteStrategyB with message: "<< message<< std::endl;
    }
};
  1. 创建一个上下文类,用于使用策略对象:
class Context {
public:
    Context(Strategy* strategy) : strategy_(strategy) {}

    void set_strategy(Strategy* strategy) {
        strategy_ = strategy;
    }

    void execute_strategy(const std::string& message) {
        strategy_->execute(message);
    }

private:
    Strategy* strategy_;
};
  1. 最后,在主函数中测试策略模式:
int main() {
    // 创建具体策略对象
    ConcreteStrategyA strategy_a;
    ConcreteStrategyB strategy_b;

    // 创建上下文对象,并设置具体策略
    Context context(&strategy_a);

    // 执行策略
    context.execute_strategy("Hello, Strategy A!");

    // 更改策略
    context.set_strategy(&strategy_b);

    // 再次执行策略
    context.execute_strategy("Hello, Strategy B!");

    return 0;
}

这个示例展示了如何使用策略模式来动态地改变对象的行为。你可以根据需要添加更多的具体策略类,并在上下文类中使用它们。

0