策略模式通过函数对象或模板替代继承,实现算法与逻辑解耦: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封装可调用对象,使策略更轻量:
立即学习“C++免费学习笔记(深入)”;
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、仿函数等:
Dbsite企业网站管理系统V1.5.0 秉承"大道至简 邦达天下"的设计理念,以灵巧、简单的架构模式构建本管理系统。可根据需求可配置多种类型数据库(当前压缩包支持Access).系统是对多年企业网站设计经验的总结。特别适合于中小型企业网站建设使用。压缩包内包含通用企业网站模板一套,可以用来了解系统标签和设计网站使用。QQ技术交流群:115197646 系统特点:1.数据与页
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适合运行时动态切换,模板则适用于编译期确定策略且追求性能的场景。基本上就这些。









