赞
踩
策略模式(Strategy Pattern)是一种行为设计模式,用于将算法家族(一组相似的算法)封装起来,使它们可以相互替换,让算法的变化独立于使用算法的客户端。
例如:
#include <iostream> using namespace std; // 定义策略接口 class Strategy { public: virtual void execute() = 0; }; // 具体策略类 A class ConcreteStrategyA : public Strategy { public: void execute() { cout << "Execute strategy A" << endl; } }; // 具体策略类 B class ConcreteStrategyB : public Strategy { public: void execute() { cout << "Execute strategy B" << endl; } }; // 环境类 class Context { private: Strategy* strategy; // 持有策略对象的引用 public: Context(Strategy* s) : strategy(s) {} void setStrategy(Strategy* s) { strategy = s; } void executeStrategy() { strategy->execute(); } }; int main() { // 创建具体策略对象 ConcreteStrategyA* strategyA = new ConcreteStrategyA(); ConcreteStrategyB* strategyB = new ConcreteStrategyB(); // 创建环境对象并设置策略对象 A Context* context = new Context(strategyA); context->executeStrategy(); // 动态切换策略对象为 B 并执行 context->setStrategy(strategyB); context->executeStrategy(); // 释放资源 delete strategyA; delete strategyB; delete context; return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。