策略模式的核心思想策略模式属于行为型设计模式允许在运行时选择算法的具体实现。其核心是将算法族封装为独立类使它们可以互相替换且算法的变化不影响使用算法的客户端。模式结构Context上下文持有一个策略对象的引用通过接口调用具体策略。Strategy抽象策略定义算法接口通常为抽象类或纯虚接口。ConcreteStrategy具体策略实现策略接口的具体算法。C实现示例#include iostream #include memory // 抽象策略类 class Strategy { public: virtual void execute() const 0; virtual ~Strategy() default; }; // 具体策略A class ConcreteStrategyA : public Strategy { public: void execute() const override { std::cout Executing Strategy A\n; } }; // 具体策略B class ConcreteStrategyB : public Strategy { public: void execute() const override { std::cout Executing Strategy B\n; } }; // 上下文类 class Context { private: std::unique_ptrStrategy strategy; public: explicit Context(std::unique_ptrStrategy strategy) : strategy(std::move(strategy)) {} void setStrategy(std::unique_ptrStrategy newStrategy) { strategy std::move(newStrategy); } void executeStrategy() const { if (strategy) { strategy-execute(); } } }; // 客户端代码 int main() { auto context Context(std::make_uniqueConcreteStrategyA()); context.executeStrategy(); // 输出: Executing Strategy A context.setStrategy(std::make_uniqueConcreteStrategyB()); context.executeStrategy(); // 输出: Executing Strategy B return 0; }应用场景需要动态切换算法时如排序、压缩算法。避免多重条件语句导致的代码臃肿。算法需要独立于客户端变化。优缺点分析优点符合开闭原则新增策略无需修改上下文。消除条件分支提升代码可维护性。缺点客户端需了解不同策略的差异。策略类数量可能过多增加系统复杂度。扩展策略模式与工厂模式结合通过工厂模式创建策略对象进一步解耦客户端与具体策略class StrategyFactory { public: static std::unique_ptrStrategy createStrategy(const std::string type) { if (type A) return std::make_uniqueConcreteStrategyA(); if (type B) return std::make_uniqueConcreteStrategyB(); return nullptr; } };实际案例游戏中的角色行为在游戏中角色的移动行为行走、奔跑、飞行可封装为不同策略运行时动态切换class MovementStrategy { public: virtual void move() const 0; }; class WalkStrategy : public MovementStrategy { /* 实现行走逻辑 */ }; class FlyStrategy : public MovementStrategy { /* 实现飞行逻辑 */ };https://github.com/sean456665/bvw_594vhttps://github.com/joshvfort/c3c_rtgdhttps://github.com/tankiahabi/5jl_9iqohttps://github.com/taimoralis/6be_9uwhhttps://github.com/dagababa/mz5_rqiv