1. 策略模式:从硬编码到灵活适配的算法解耦之道
记得刚入行那会儿,我也像光头强一样沉迷于继承大法。直到某个深夜,当我第N次为了修改一个基础行为而被迫调整几十个子类时,才真正体会到策略模式的精妙之处。策略模式不是简单的"把方法抽出来",而是一种从根本上改变我们组织代码的思维方式。
1.1 从业务场景看策略模式的价值
在真实的电商系统开发中,我遇到过这样一个典型案例:支付渠道的接入。最初我们采用硬编码方式:
class Payment { public: void pay(const string& type) { if (type == "alipay") { // 支付宝支付逻辑 } else if (type == "wechat") { // 微信支付逻辑 } // 更多if-else... } };这种写法在只有两三种支付方式时还能应付,但当需要接入银联、PayPal、数字货币等十几种支付方式时,代码就变成了维护噩梦。更糟的是,每次新增支付方式都需要修改核心类,违反开闭原则。
1.2 策略模式的标准化实现
策略模式的经典实现包含三个角色:
- Context(上下文):维护策略引用(如Bear类)
- Strategy(策略接口):定义算法接口(如Hibernation_Behavior)
- ConcreteStrategy(具体策略):实现具体算法(如Hibernation_able)
在C++中,我们通常使用运行时多态实现:
// 策略接口 class PaymentStrategy { public: virtual void pay(double amount) = 0; virtual ~PaymentStrategy() = default; }; // 具体策略 class AlipayStrategy : public PaymentStrategy { public: void pay(double amount) override { // 支付宝具体实现 } }; // 上下文 class PaymentContext { private: unique_ptr<PaymentStrategy> strategy; public: explicit PaymentContext(unique_ptr<PaymentStrategy>&& s) : strategy(std::move(s)) {} void executePayment(double amount) { strategy->pay(amount); } };2.1 策略选择的动态化实现
在实际项目中,策略的选择往往需要动态决定。我们可以结合工厂模式实现更灵活的配置:
class StrategyFactory { public: static unique_ptr<PaymentStrategy> create(const string& type) { if (type == "alipay") return make_unique<AlipayStrategy>(); if (type == "wechat") return make_unique<WechatPayStrategy>(); throw invalid_argument("Unsupported payment type"); } }; // 使用示例 auto strategy = StrategyFactory::create(config.getPaymentMethod()); PaymentContext context(std::move(strategy)); context.executePayment(100.00);2.2 策略模式与模板的结合
对于性能敏感的场景,可以使用编译时多态(模板策略):
template<typename Strategy> class PaymentContext { Strategy strategy; public: void executePayment(double amount) { strategy.pay(amount); } }; // 使用 PaymentContext<AlipayStrategy> context; context.executePayment(100.00);这种方式避免了虚函数开销,但牺牲了运行时灵活性。
3.1 策略模式的进阶应用:带状态的策略
某些场景下,策略可能需要维护状态。例如折扣策略可能需要访问用户等级:
class DiscountStrategy { public: virtual double calculate(double price, User& user) = 0; }; class VipDiscount : public DiscountStrategy { public: double calculate(double price, User& user) override { return price * (1 - 0.1 * user.getVipLevel()); } }; class DiscountContext { unique_ptr<DiscountStrategy> strategy; public: void setStrategy(unique_ptr<DiscountStrategy>&& s) { strategy = std::move(s); } double applyDiscount(double price, User& user) { return strategy->calculate(price, user); } };3.2 策略组合模式
复杂业务中,可能需要组合多个策略。例如电商促销可能同时应用满减、折扣和优惠券:
class CompositeStrategy : public DiscountStrategy { vector<unique_ptr<DiscountStrategy>> strategies; public: void addStrategy(unique_ptr<DiscountStrategy>&& s) { strategies.push_back(std::move(s)); } double calculate(double price, User& user) override { for (auto& s : strategies) { price = s->calculate(price, user); } return price; } };4.1 策略模式的典型误用
在实践中,我发现开发者常犯的几个错误:
- 过度设计:简单if-else就能解决的问题强行使用策略模式
- 策略膨胀:创建过多细粒度策略类导致管理困难
- 上下文污染:在上下文中添加了与策略无关的逻辑
经验法则:当发现自己在写大量条件判断,且这些判断代表不同的算法变体时,才考虑策略模式。
4.2 性能考量与优化
虽然策略模式提供了灵活性,但也带来一些开销:
- 虚函数调用开销(通常可忽略)
- 对象创建销毁成本(可使用对象池优化)
- 内存占用(共享无状态策略可减少内存使用)
无状态策略的最佳实践:
class StatelessStrategy { public: static double compute(double input) { // 无成员变量的纯计算 } };5.1 策略模式与其他模式的关系
策略模式常与其他模式配合使用:
- 工厂模式:创建具体策略
- 模板方法模式:定义算法骨架
- 装饰器模式:动态添加策略
例如,结合装饰器实现可叠加的过滤策略:
class FilterStrategy { public: virtual vector<Product> filter(vector<Product> products) = 0; }; class PriceFilter : public FilterStrategy { double maxPrice; public: explicit PriceFilter(double p) : maxPrice(p) {} vector<Product> filter(vector<Product> products) override { // 过滤逻辑 } }; class CompositeFilter : public FilterStrategy { vector<shared_ptr<FilterStrategy>> filters; public: void addFilter(shared_ptr<FilterStrategy> f) { filters.push_back(f); } vector<Product> filter(vector<Product> products) override { for (auto& f : filters) { products = f->filter(products); } return products; } };5.2 现代C++中的策略模式实现
C++11后的新特性让策略模式实现更优雅:
- 使用function和lambda替代策略接口
- 用shared_ptr管理策略生命周期
- 基于type_erasure的通用策略容器
using Strategy = function<void(double)>; class PaymentProcessor { Strategy strategy; public: void setStrategy(Strategy s) { strategy = s; } void process(double amount) { strategy(amount); } }; // 使用 PaymentProcessor processor; processor.setStrategy([](double amt) { // lambda实现策略 }); processor.process(100.00);6.1 策略模式在框架设计中的应用
优秀框架都大量使用策略模式提供扩展点。例如:
- STL中的allocator
- 排序算法的比较函数
- 容器的大小策略
自定义内存分配器示例:
template<typename T, typename Allocator = std::allocator<T>> class CustomContainer { Allocator alloc; public: T* create() { return alloc.allocate(1); } void destroy(T* p) { alloc.deallocate(p, 1); } };6.2 策略模式的测试考量
策略模式的一个优势是便于单元测试:
- 可以mock策略进行隔离测试
- 每个策略可以独立测试
- 上下文无需关心具体策略实现
测试示例:
TEST(PaymentTest, AlipayStrategyTest) { AlipayStrategy strategy; MockPaymentService service; EXPECT_CALL(service, submit(_)).Times(1); strategy.pay(100.00, service); } TEST(PaymentTest, ContextTest) { auto mockStrategy = make_unique<MockPaymentStrategy>(); EXPECT_CALL(*mockStrategy, pay(_)).Times(1); PaymentContext context(std::move(mockStrategy)); context.executePayment(100.00); }7.1 策略模式与业务规则引擎
对于复杂的业务规则系统,策略模式可以演化为规则引擎:
class BusinessRule { public: virtual bool evaluate(Context&) = 0; virtual void execute(Context&) = 0; }; class RuleEngine { vector<unique_ptr<BusinessRule>> rules; public: void addRule(unique_ptr<BusinessRule> rule) { rules.push_back(std::move(rule)); } void run(Context& ctx) { for (auto& rule : rules) { if (rule->evaluate(ctx)) { rule->execute(ctx); } } } };7.2 策略模式的领域特定实现
在不同领域,策略模式有特定形态:
- 游戏AI中的行为树
- 金融系统中的风险计算引擎
- 编译器中的优化pass
游戏AI示例:
class AIBehavior { public: virtual void update(NPC& npc) = 0; }; class PatrolBehavior : public AIBehavior { void update(NPC& npc) override { // 巡逻逻辑 } }; class CombatBehavior : public AIBehavior { void update(NPC& npc) override { // 战斗逻辑 } }; class AIAgent { unique_ptr<AIBehavior> behavior; public: void setBehavior(unique_ptr<AIBehavior> b) { behavior = std::move(b); } void update() { behavior->update(*this); } };8.1 策略模式的演进与替代
随着语言发展,有些场景有更现代的替代方案:
- 函数式编程的高阶函数
- 模式匹配(如Rust的match)
- 策略作为服务(微服务架构)
Rust模式匹配示例:
enum PaymentMethod { Alipay, WechatPay, CreditCard(String) } fn process_payment(method: PaymentMethod, amount: f64) { match method { PaymentMethod::Alipay => alipay::pay(amount), PaymentMethod::WechatPay => wechat::pay(amount), PaymentMethod::CreditCard(num) => card::pay(num, amount) } }8.2 策略模式的局限性
策略模式并非银弹,其局限性包括:
- 客户端必须了解不同策略
- 策略间通信可能复杂
- 可能增加对象数量
对于简单场景,考虑更轻量的方案:
// 使用variant替代策略层次 using PaymentAction = variant<AlipayAction, WechatAction>; void process_payment(PaymentAction action, double amount) { visit([amount](auto&& act) { act.pay(amount); }, action); }9.1 策略模式的最佳实践
根据多年经验,我总结的策略模式实践要点:
- 明确识别变化点:只有真正可能变化的算法才值得抽象
- 保持策略纯净:避免在策略中维护与算法无关的状态
- 平衡粒度:策略划分过细会导致类爆炸,过粗则失去灵活性
- 文档化策略:明确每个策略的适用场景和约束条件
9.2 策略模式的架构影响
在架构层面,策略模式可以:
- 将业务规则与技术实现分离
- 实现核心领域与外部适配的解耦
- 支持蓝绿部署等高级部署模式
微服务架构中的策略示例:
// 支付策略微服务客户端 class PaymentServiceClient { PaymentStrategy& getStrategy(string type) { // 远程获取策略配置 auto config = paymentService.getConfig(type); return config.createStrategy(); } };10.1 从策略模式到领域驱动设计
策略模式自然导向DDD中的一些重要概念:
- 领域服务:无状态的策略实现
- 规约模式:可组合的业务规则
- 策略模式:领域模型的行为扩展
DDD中的价格计算策略:
class PricingStrategy { public: virtual Money calculate(Order& order) = 0; }; class MemberPricing : public PricingStrategy { Money calculate(Order& order) override { // 会员价计算逻辑 } }; class PricingService { unique_ptr<PricingStrategy> strategy; public: Money calculatePrice(Order& order) { return strategy->calculate(order); } };10.2 策略模式与SOLID原则
策略模式完美体现了SOLID原则:
- 单一职责:每个策略只关注一个算法
- 开闭原则:新增策略无需修改现有代码
- 里氏替换:策略接口可任意替换
- 接口隔离:策略接口保持最小化
- 依赖倒置:依赖抽象而非实现
11.1 策略模式的性能优化技巧
在高性能场景下的优化经验:
- 策略缓存:避免重复创建策略对象
- 数据局部性:将频繁使用的策略放在连续内存
- 热交换优化:使用读写锁保护策略切换
缓存示例:
class StrategyCache { unordered_map<string, shared_ptr<Strategy>> cache; mutable shared_mutex mtx; public: shared_ptr<Strategy> get(const string& key) { shared_lock lock(mtx); if (auto it = cache.find(key); it != cache.end()) { return it->second; } lock.unlock(); unique_lock wlock(mtx); auto strategy = Factory::create(key); cache.emplace(key, strategy); return strategy; } };11.2 策略模式与并发编程
多线程环境下使用策略模式的注意事项:
- 无状态策略:最安全,天然线程安全
- 有状态策略:需要适当的同步机制
- 策略切换:需要保证原子性和可见性
线程安全的策略上下文:
class ThreadSafeContext { shared_ptr<Strategy> strategy; mutable mutex mtx; public: void setStrategy(shared_ptr<Strategy> s) { lock_guard lock(mtx); strategy = s; } void execute() { shared_ptr<Strategy> local; { lock_guard lock(mtx); local = strategy; } local->execute(); } };12.1 策略模式的反模式
警惕这些策略模式的错误用法:
- 策略知晓上下文:导致双向依赖
- 策略层次过深:过度设计
- 策略参数爆炸:接口过于复杂
不良实践示例:
// 反模式:策略知晓上下文 class BadStrategy { public: virtual void execute(Context&) = 0; }; class Context { BadStrategy* strategy; public: void setStrategy(BadStrategy* s) { strategy = s; } void run() { strategy->execute(*this); // 策略反向依赖上下文 } };12.2 策略模式的调试技巧
调试策略模式系统的有效方法:
- 策略日志:记录策略选择和执行过程
- 策略标记:为每个策略添加唯一标识
- 策略模拟:在测试中注入特定策略
调试日志示例:
class LoggingStrategy : public PaymentStrategy { shared_ptr<PaymentStrategy> wrapped; public: explicit LoggingStrategy(shared_ptr<PaymentStrategy> s) : wrapped(s) {} void pay(double amount) override { log("Executing payment with strategy: " + typeid(*wrapped).name()); wrapped->pay(amount); } };13.1 策略模式与设计原则的深层关系
策略模式体现了这些核心设计思想:
- 关注点分离:算法实现与使用解耦
- 组合优于继承:通过组合获得灵活性
- 面向接口编程:依赖抽象而非实现
- 控制反转:将算法选择权外移
13.2 策略模式的历史演进
策略模式的概念发展:
- 早期OOP:通过继承实现多态
- GoF模式:正式定义为行为模式
- 现代实现:结合泛型编程和函数式特性
14.1 策略模式在不同语言中的实现差异
各语言对策略模式的支持:
- Java/C#:基于接口的经典实现
- C++:可使用模板策略
- Python/JavaScript:鸭子类型更灵活
- Go:通过接口和组合实现
Python的鸭子类型实现:
class PaymentStrategy: def pay(self, amount): pass class AlipayStrategy: def pay(self, amount): # 实现支付逻辑 pass class PaymentContext: def __init__(self, strategy): self.strategy = strategy def execute_payment(self, amount): self.strategy.pay(amount)14.2 策略模式与函数式编程
函数式语言中的策略等价物:
- 高阶函数:函数作为参数传递
- 模块系统:实现策略的封装和组合
- 类型类:隐式策略解析
Haskell示例:
class PaymentStrategy a where pay :: a -> Double -> IO () data Alipay = Alipay instance PaymentStrategy Alipay where pay _ amount = putStrLn $ "Alipay支付: " ++ show amount processPayment :: PaymentStrategy a => a -> Double -> IO () processPayment strategy amount = pay strategy amount15.1 策略模式在框架中的经典案例
知名框架中的策略应用:
- STL排序:比较函数作为策略
- Java Collections:Comparator接口
- React:渲染策略
- Spring:各种策略接口
STL中的策略示例:
vector<int> nums = {3,1,4,2}; // 升序策略 sort(nums.begin(), nums.end(), less<int>()); // 降序策略 sort(nums.begin(), nums.end(), greater<int>()); // 自定义策略 sort(nums.begin(), nums.end(), [](int a, int b) { return abs(a) < abs(b); });15.2 策略模式的扩展变体
基于经典策略模式的衍生模式:
- 策略代理:远程策略执行
- 策略链:责任链与策略结合
- 策略装饰器:动态增强策略
策略链示例:
class ValidationStrategy { public: virtual bool validate(string input) = 0; }; class ValidationChain : public ValidationStrategy { vector<unique_ptr<ValidationStrategy>> strategies; public: void addStrategy(unique_ptr<ValidationStrategy> s) { strategies.push_back(std::move(s)); } bool validate(string input) override { for (auto& s : strategies) { if (!s->validate(input)) return false; } return true; } };16.1 策略模式与测试驱动开发
TDD中策略模式的应用技巧:
- 先定义策略接口:从测试出发设计抽象
- mock策略:隔离测试上下文
- 测试策略组合:验证交互逻辑
测试示例:
TEST(ValidationTest, StrategyComposition) { auto lengthCheck = make_unique<MockValidation>(); auto formatCheck = make_unique<MockValidation>(); EXPECT_CALL(*lengthCheck, validate(_)).WillOnce(Return(true)); EXPECT_CALL(*formatCheck, validate(_)).WillOnce(Return(false)); ValidationChain chain; chain.addStrategy(std::move(lengthCheck)); chain.addStrategy(std::move(formatCheck)); ASSERT_FALSE(chain.validate("test")); }16.2 策略模式的文档化实践
如何有效文档化策略系统:
- 策略目录:列出所有可用策略
- 决策矩阵:指导策略选择的条件
- 示例代码:展示典型用法
- 性能特征:各策略的资源消耗
文档示例:
## 缓存策略文档 ### 可用策略 1. `LRUStrategy`: 最近最少使用 - 适用场景: 访问具有局部性 - 时间复杂度: O(1) 2. `FIFOStrategy`: 先进先出 - 适用场景: 公平缓存 - 时间复杂度: O(1) ### 选择指南 | 条件 | 推荐策略 | |--------------------|------------| | 内存受限 | LRU | | 顺序访问模式 | FIFO | | 随机访问模式 | LRU |17.1 策略模式与领域特定语言
使用DSL配置策略的进阶模式:
// 策略DSL示例 auto strategy = PaymentStrategyBuilder() .withAlipay() .withRetry(3) .withFallback(wechatPay) .build(); // 等价于 PaymentStrategy strategy = RetryStrategy( FallbackStrategy( AlipayStrategy(), wechatPay ), 3 );17.2 策略模式的元编程实现
利用C++模板元编程实现编译时策略:
template<typename Strategy> struct Context { void execute() { Strategy::execute(); } }; struct FastStrategy { static void execute() { /* 快速算法 */ } }; struct SafeStrategy { static void execute() { /* 安全算法 */ } }; // 使用 Context<FastStrategy> ctx; ctx.execute();18.1 策略模式与设计系统的关系
在设计系统中,策略模式体现为:
- 主题系统:不同的渲染策略
- 布局引擎:响应式布局策略
- 交互管理器:不同设备的交互策略
UI主题策略示例:
class ThemeStrategy { public: virtual Color backgroundColor() = 0; virtual Color textColor() = 0; }; class DarkTheme : public ThemeStrategy { Color backgroundColor() override { return Color::Black; } Color textColor() override { return Color::White; } }; class UIContext { shared_ptr<ThemeStrategy> theme; public: void applyTheme() { window.setBgColor(theme->backgroundColor()); // 应用其他主题属性 } };18.2 策略模式与架构模式
策略模式在架构层面的应用:
- 插件架构:每个插件实现特定策略
- 微内核:核心系统+可替换策略
- 管道过滤器:过滤策略的可插拔
插件架构示例:
// 核心系统 class PluginSystem { vector<unique_ptr<Plugin>> plugins; public: void addPlugin(unique_ptr<Plugin> p) { plugins.push_back(std::move(p)); } void process(Data& data) { for (auto& p : plugins) { p->apply(data); } } }; // 策略插件 class FilterPlugin : public Plugin { void apply(Data& data) override { // 过滤策略实现 } };19.1 策略模式的代码异味识别
这些迹象表明策略模式可能被误用:
- 策略间高度耦合:策略需要知道其他策略
- 上下文过于复杂:承担了非策略相关职责
- 策略膨胀:过多细小策略类
- 频繁策略切换:运行时不断更换策略
重构信号示例:
// 反例:策略间耦合 class StrategyA { void execute() { if (someCondition) { StrategyB().execute(); // 直接依赖其他策略 } } };19.2 策略模式的替代方案
当策略模式不适用时考虑:
- 状态模式:对于状态驱动的行为变化
- 命令模式:需要支持撤销/重做时
- 模板方法:固定算法骨架时
- 简单函数:当逻辑足够简单时
状态模式对比示例:
class State { public: virtual void handle() = 0; }; class Context { unique_ptr<State> state; public: void changeState(unique_ptr<State> s) { state = std::move(s); } void request() { state->handle(); } };20.1 策略模式的性能基准测试
通过基准测试量化策略开销(使用Google Benchmark):
static void BM_StrategyPattern(benchmark::State& state) { Context ctx(make_unique<FastStrategy>()); for (auto _ : state) { ctx.execute(); } } BENCHMARK(BM_StrategyPattern); static void BM_DirectCall(benchmark::State& state) { for (auto _ : state) { directCall(); } } BENCHMARK(BM_DirectCall);20.2 策略模式的编译时优化
通过CRTP模式消除虚函数开销:
template<typename Derived> class StrategyBase { public: void execute() { static_cast<Derived*>(this)->executeImpl(); } }; class ConcreteStrategy : public StrategyBase<ConcreteStrategy> { public: void executeImpl() { // 具体实现 } }; template<typename S> class Context { S strategy; public: void run() { strategy.execute(); } };21.1 策略模式与设计决策记录
使用ADR记录策略选择:
# 架构决策记录:支付策略实现 ## 状态 2023-05-20 提议 2023-05-25 已接受 ## 决策 采用策略模式实现多支付渠道,原因: 1. 支付方式可能频繁变更 2. 需要支持运行时动态切换 3. 各支付方式算法差异大 ## 后果 - 新增支付方式无需修改核心代码 - 增加了一定程度的间接性 - 需要维护策略工厂21.2 策略模式的演进式设计
策略模式支持架构演进:
- 初期:简单if-else实现
- 中期:重构为基本策略模式
- 成熟期:策略工厂+配置化
- 扩展期:策略服务化
演进示例:
// 阶段1:简单实现 void processPayment(string type) { if (type == "alipay") processAlipay(); else if (type == "wechat") processWechat(); } // 阶段2:策略模式 interface PaymentStrategy { void pay(); } class AlipayStrategy implements PaymentStrategy { ... } // 阶段3:配置化 var strategy = StrategyFactory.create(config.getType()); strategy.pay(); // 阶段4:服务化 var strategy = PaymentServiceClient.getStrategy(type); strategy.pay();22.1 策略模式与代码可读性
良好的策略模式实现应该:
- 策略命名清晰:如FastSortStrategy而非StrategyImpl
- 上下文职责单一:不混杂非策略逻辑
- 接口设计精简:避免臃肿的策略接口
- 文档注释完整:说明各策略适用场景
22.2 策略模式的代码审查要点
审查策略模式实现时关注:
- 策略是否真正独立变化:还是伪装的if-else
- 上下文是否保持简单:不承担策略职责
- 策略接口是否稳定:频繁变更的接口是设计问题
- 策略创建成本:是否适合频繁创建销毁
23.1 策略模式与设计质量指标
策略模式如何影响代码质量指标:
- 可维护性:通过分离关注点提高
- 可扩展性:新增策略不影响现有代码
- 可测试性:策略可独立测试
- 可读性:可能因间接性略有降低
23.2 策略模式的量化评估
评估策略模式实施效果的指标:
- 策略类数量:反映设计粒度
- 策略变更频率:验证是否真正独立变化
- 上下文修改频率:理想情况下应很少修改
- 策略复用率:衡量设计有效性
24.1 策略模式与团队协作
策略模式对团队开发的影响:
- 并行开发:不同成员可独立实现策略
- 知识共享:通过策略接口明确约定
- 代码所有权:清晰的功能边界
- 新人上手:通过示例策略快速理解
24.2 策略模式的持续演进
维护策略模式系统的建议:
- 定期评审策略:合并相似策略
- 监控策略使用:识别冷策略
- 收集策略指标:如执行成功率
- 渐进式重构:不断优化策略接口
25.1 策略模式的跨平台应用
在跨平台开发中的应用:
- 平台特定策略:不同平台的实现
- 渲染策略:针对不同设备的渲染
- 存储策略:本地与云端存储切换
跨平台示例:
class PlatformStrategy { public: virtual void showDialog() = 0; }; class AndroidDialog : public PlatformStrategy { void showDialog() override { // Android实现 } }; class IOSDialog : public PlatformStrategy { void showDialog() override { // iOS实现 } }; class CrossPlatformApp { unique_ptr<PlatformStrategy> strategy; public: void showSettings() { strategy->showDialog(); } };25.2 策略模式与设计系统演进
从策略模式到设计系统的路径:
- 识别变体:发现需要灵活变化的部分
- 定义接口:抽象出策略契约
- 实现策略:创建具体变体实现
- 构建生态:形成可复用的策略库
- 完善工具:开发策略配置和管理工具
26.1 策略模式的自动化测试策略
针对策略模式的测试方法:
- 策略接口测试:验证所有策略共有的前置条件
- 策略特性测试:验证每个策略的特定行为
- 策略组合测试:测试策略间的交互
- 性能基准测试:比较不同策略的性能
测试金字塔示例:
策略接口测试 / \ 策略特性测试 策略组合测试 \ / 性能基准测试26.2 策略模式的异常处理模式
策略模式中的错误处理建议:
- 策略特定错误:由策略自己处理
- 通用错误:通过策略接口上报
- 回退策略:主策略失败时启用备用
- 错误转换:将策略错误转为上下文错误
异常处理示例:
class RetryStrategy : public PaymentStrategy { shared_ptr<PaymentStrategy> strategy; int maxRetries; public: void pay(double amount) override { for (int i = 0; i <= maxRetries; ++i) { try { strategy->pay(amount); return; } catch (const PaymentError& e) { if (i == maxRetries) throw; } } } };27.1 策略模式与设计令牌
使用设计令牌驱动策略:
class DesignTokenStrategy { public: virtual Color getColor(string role) = 0; virtual Font getFont(string type) = 0; }; class LightThemeTokens : public DesignTokenStrategy { Color getColor(string role) override { static map<string, Color> colors = { {"primary", Color::Blue}, {"background", Color::White} }; return colors.at(role); } // 字体实现类似 }; class StyledComponent { shared_ptr<DesignTokenStrategy> tokens; public: void render() { auto bg = tokens->getColor("background"); // 使用令牌渲染 } };27.2 策略模式与动态配置
结合配置系统实现动态策略:
class StrategyConfig { public: virtual string getStrategyType() = 0; virtual JsonValue getConfig() = 0; }; class DynamicContext { unique_ptr<Strategy> strategy; shared_ptr<StrategyConfig> config; public: void reload() { strategy = Factory::create( config->getStrategyType(), config->getConfig() ); } void execute() { strategy->execute(); } };28.1 策略模式与性能调优
性能敏感场景的优化策略:
- 策略预加载:启动时加载常用策略
- 策略缓存:缓存策略实例
- 无锁策略:使用原子操作切换策略
- SIMD策略:向量化处理策略
无锁策略示例:
class AtomicStrategyContext { atomic<Strategy*> strategy; public: void setStrategy(Strategy* s) { strategy.store(s, memory_order_release); } void execute() { auto s = strategy.load(memory_order_acquire); s->execute(); } };28.2 策略模式与内存管理
策略对象生命周期管理:
- 静态策略:单例或静态实例
- 共享策略:shared_ptr管理
- 独占策略:unique_ptr管理
- 池化策略:对象池复用
策略池示例:
class StrategyPool { map<TypeIndex, vector<unique_ptr<Strategy>>> pool; mutex mtx; public: template<typename S> S* acquire() { lock_guard lock(mtx); auto& list = pool[typeid(S)]; if (list.empty()) { return new S(); } auto ptr = list.back().release(); list.pop_back(); return static_cast<S*>(ptr); } template<typename S> void release(S* s) { lock_guard lock(mtx); pool[typeid(S)].emplace_back(s); } };29.1 策略模式与设计系统主题
在设计系统中实现主题策略:
class ThemeStrategy { public: virtual ColorPalette getColors() = 0; virtual Typography getTypography() = 0; }; class DarkTheme : public ThemeStrategy { ColorPalette getColors() override { return { .primary = Color::DarkBlue, .background = Color::Black }; } // 其他实现 }; class ThemedComponent { shared_ptr<ThemeStrategy> theme; public: void render() { auto colors = theme->getColors(); // 使用主题渲染 } };29.2 策略模式与无障碍设计
无障碍策略的实现:
class AccessibilityStrategy { public: virtual FontSize getFontSize() = 0; virtual ColorContrast getContrast() = 0; }; class HighContrastStrategy : public AccessibilityStrategy { FontSize getFontSize() override { return FontSize::Large; } ColorContrast getContrast() override { return ColorContrast::High; } }; class AccessibleUI { shared_ptr<AccessibilityStrategy> strategy; public: void applyAccessibility() { setFont(strategy->getFontSize()); setContrast(strategy->getContrast()); } };30.1 策略模式与设计系统文档
文档化策略系统的建议:
- 策略目录:列出所有可用策略
- 选择指南:何时使用哪种策略
- 示例代码:典型用法示例
- 扩展指南:如何添加新策略
文档结构示例:
# 设计