您的位置:首页 >C++策略模式与函数对象结合应用
发布于2025-09-21 阅读(0)
扫一扫,手机访问
策略模式通过函数对象或模板替代继承,实现算法与逻辑解耦:1. 用std::function封装可调用对象,支持运行时动态切换策略;2. 用模板参数传递策略,编译期绑定,提升性能。

在C++中,策略模式常用于将算法的实现与使用逻辑解耦。通过结合函数对象(仿函数)或可调用对象(如lambda、std::function),可以更灵活地定义和切换策略,同时避免传统继承带来的复杂性。
传统策略模式依赖抽象基类和具体子类来实现不同算法:
struct Strategy {
virtual ~Strategy() = default;
virtual void execute() = 0;
};
struct ConcreteStrategyA : Strategy {
void execute() override { / 算法A / }
};
struct Context {
explicit Context(std::unique_ptr<Strategy> s) : strategy(std::move(s)) {}
void run() { strategy->execute(); }
private:
std::unique_ptr<Strategy> strategy;
};
这种方式清晰但需要定义多个类,略显繁琐。
可以用std::function封装可调用对象,使策略更轻量:
class FlexibleContext {
public:
using StrategyFunc = std::function<void()>;
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() { /* 普通函数 */ }
int main() {
FlexibleContext ctx([]{ std::cout << "Lambda strategy\n"; });
ctx.run();
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)) {}
void run() { strategy(); }private:
Strategy strategy;
};
支持任意可调用类型,编译期绑定,效率更高:
auto lambda = [] { std::cout << "Fast lambda\n"; };
TemplateContext ctx(lambda);
ctx.run(); // 内联调用,无开销
这种组合方式让策略模式更简洁、高效。使用std::function适合运行时动态切换,模板则适用于编译期确定策略且追求性能的场景。基本上就这些。
上一篇:七猫小说如何查看阅读记录
下一篇:小米红包助手设置教程
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9