我正在讨论在 C++ 中实现策略模式的最佳方式。到目前为止,我一直使用标准方式,其中上下文有一个指向基本策略类的指针,如下所示:
class AbstractStrategy{
public:
virtual void exec() = 0;
}
class ConcreteStrategyA{
public:
void exec();
}
class ConcreteStrategyB{
public:
void exec();
}
class Context{
public:
Context(AbstractStrategy* strategy):strategy_(strategy){}
~Context(){
delete strategy;
}
void run(){
strategy->exec();
}
private:
AbstractStrategy* strategy_;
由于指向对象的指针会导致不良行为,因此我一直在寻找一种更安全的方法来实现此模式,然后我找到了 this question其中 std::function
被提议作为处理这种模式的更好方法。
有人可以更好地解释 std::function
是如何工作的,也许可以举一个策略模式的例子吗?
最佳答案
请注意,单一方法对象与函数同构,而策略只是单一方法对象。
所以基本上,你摆脱了所有的类,你只使用 std::function<void()>
相反:
class Context {
public:
template<typename F>
explicit Context(F strategy) : strategy(std::move(strategy)) { }
void run() { strategy(); }
private:
std::function<void()> strategy;
};
然后您可以将任何可调用对象传递给 Context
的构造函数:
Context ctx([] { std::cout << "Hello, world!\n"; });
ctx.run();
关于c++ - 如何在 C++ 中使用 std::function 实现策略模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29031782/