

























策略模式(Strategy Pattern)是一种行为型设计模式,其核心思想是定义一组算法,将每个算法封装为独立的类,使它们可以互相替换12。该模式通过将算法与使用它的客户端解耦,实现运行时动态切换算法,避免使用多重条件判断语句(如if-else)
优势:
局限:
普通代码
// 策略接口 class Strategy { public: virtual void execute() = 0; }; // 具体策略 class StrategyA : public Strategy { public: void execute() override { /* 实现A */ } }; // 上下文类 class Context { private: Strategy* strategy_; public: void setStrategy(Strategy* s) { strategy_ = s; } void action() { strategy_->execute(); } };
#include <iostream> // 策略接口 template<typename T> class OperationStrategy { public: virtual T execute(T a, T b) = 0; virtual ~OperationStrategy() = default; }; // 具体策略 template<typename T> class AddOperation : public OperationStrategy<T> { public: T execute(T a, T b) override { return a + b; } }; template<typename T> class MultiplyOperation : public OperationStrategy<T> { public: T execute(T a, T b) override { return a * b; } }; // 上下文类 template<typename T> class Context { private: OperationStrategy<T>* strategy_; public: // 构造函数接受策略对象 Context(OperationStrategy<T>* strategy) : strategy_(strategy) {} T executeStrategy(T a, T b) { return strategy_->execute(a, b); } };
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。