C++策略模式与函数对象结合应用
策略模式通过函数对象或模板替代继承,实现算法与逻辑解耦:1.用std::function封装可调用对象,支持运行时动态切换策略;2.用模板参数传递策略,编译期绑定,提升性能。
策略模式通过函数对象或模板替代继承,实现算法与逻辑解耦: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 s) : strategy(std::move(s)) {}
void run() { strategy->execute(); }
private:
std::unique_ptr strategy;
};
这种方式清晰但需要定义多个类,略显繁琐。
使用函数对象替代继承
可以用std::function封装可调用对象,使策略更轻量:
class FlexibleContext {
public:
using StrategyFunc = std::function;
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的虚函数开销:
templateclass 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适合运行时动态切换,模板则适用于编译期确定策略且追求性能的场景。基本上就这些。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















