策略模式通过函数对象或模板替代继承,实现算法与逻辑解耦:1. 用std::function封装可调用对象,支持运行时动态切换策略;2. 用模板参数传递策略,编译期绑定,提升性能。

在C++中,策略模式常用于将算法的实现与使用逻辑解耦。通过结合函数对象(仿函数)或可调用对象(如lambda、std::function),可以更灵活地定义和切换策略,同时避免传统继承带来的复杂性。
传统策略模式依赖抽象基类和具体子类来实现不同算法:
struct Strategy {
virtual ~Strategy() = default;
virtual void execute() = 0;
};
<p>struct ConcreteStrategyA : Strategy {
void execute() override { /<em> 算法A </em>/ }
};</p><p>struct Context {
explicit Context(std::unique_ptr<Strategy> s) : strategy(std::move(s)) {}
void run() { strategy->execute(); }
private:
std::unique_ptr<Strategy> strategy;
};</p>这种方式清晰但需要定义多个类,略显繁琐。
可以用std::function封装可调用对象,使策略更轻量:
立即学习“C++免费学习笔记(深入)”;
class FlexibleContext {
public:
using StrategyFunc = std::function<void()>;
<pre class='brush:php;toolbar:false;'>explicit FlexibleContext(StrategyFunc func) : strategy(std::move(func)) {}
void run() { strategy(); }
void set_strategy(StrategyFunc func) { strategy = std::move(func); }private: StrategyFunc strategy; };
这样就可以传入函数指针、lambda、仿函数等:
void function_strategy() { /* 普通函数 */ }
<p>int main() {
FlexibleContext ctx([]{ std::cout << "Lambda strategy\n"; });
ctx.run();</p><pre class='brush:php;toolbar:false;'>ctx.set_strategy(function_strategy);
ctx.run();
ctx.set_strategy(std::bind(&MyClass::method, myObj));
ctx.run();}
使用模板避免std::function的虚函数开销:
template<typename Strategy>
class TemplateContext {
public:
explicit TemplateContext(Strategy s) : strategy(std::move(s)) {}
<pre class='brush:php;toolbar:false;'>void run() { strategy(); }private: Strategy strategy; };
支持任意可调用类型,编译期绑定,效率更高:
auto lambda = [] { std::cout << "Fast lambda\n"; };
TemplateContext ctx(lambda);
ctx.run(); // 内联调用,无开销
这种组合方式让策略模式更简洁、高效。使用std::function适合运行时动态切换,模板则适用于编译期确定策略且追求性能的场景。基本上就这些。
以上就是C++策略模式与函数对象结合使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号