序言
还是参考的菜鸟教程,会C++的还是看C++的方式来得舒服。
.
理解
使用符合UML规范的便于理解和回忆,接口其实就是普通的基类
.
源码
strategy.h
/// 策略class Strategy{public: virtual ~Strategy(); virtual int operation(const int& num1, const int& num2) = 0;};/// 加策略class AddOperation : public Strategy{public: int operation(const int &num1, const int &num2) override;};/// 减策略class SubtractOperation : public Strategy{public: int operation(const int &num1, const int &num2) override;};/// 上下文class Context{public: explicit Context(Strategy *strategy); ~Context(); 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会根据其拥有的策略进行运算。
来源地址:https://blog.csdn.net/SBKnight/article/details/132172760