有没有可能实现状态设计模式在c++没有动态多态性?



假设我有以下c++代码

class ControlAlgorithm {
public:
virtual void update() = 0;
virtual void enable() = 0;
virtual void disable() = 0;
};
class Algorithm_A : public ControlAlgorithm {
public:
void update();
void enable();
void disable();
};
class Algorithm_B : public ControlAlgorithm {
public:
void update();
void enable();
void disable();
};
Algorithm_A algorithm_A;
Algorithm_B algorithm_B;
ControlAlgorithm *algorithm;

假设我想在运行时基于一些外部事件在algorithm_Aalgorithm_B之间切换(基本上我要实现状态设计模式)。因此,algorithm指针指向algorithm_Aalgorithm_B对象。我的问题是,是否有任何方法如何实现在运行时算法之间动态切换的能力,而没有虚拟方法常见的接口,例如奇怪的反复出现的模板模式?

您可以使用复合而不是继承。如下所示,例如:

#include <iostream>
#include <functional>
struct control_algorithm {
const std::function<void()> update;
const std::function<void()> enable;
const std::function<void()> edit;
};
control_algorithm make_algorithm_A() {
return {
[]() { std::cout << "update An"; },
[]() { std::cout << "enable An"; },
[]() { std::cout << "edit An"; },
};
}
control_algorithm make_algorithm_B() {
return {
[]() { std::cout << "update Bn"; },
[]() { std::cout << "enable Bn"; },
[]() { std::cout << "edit Bn"; },
};
}
int main()
{
auto algorithm_A = make_algorithm_A();
auto algorithm_B = make_algorithm_B();
auto control = algorithm_A;
//auto control = algorithm_B;
}

最新更新