我最近在中断一段时间后回到了 C++ 开发,并且有一个关于 状态设计模式的实现。我正在使用 Vanilla 模式,完全一样 根据 GoF 的书。
我的问题是状态机本身是基于一些用作 嵌入式系统 - 因此设计是固定的且无法更改。这导致 两个状态(特别是)之间的循环依赖,我正在尝试 解决这个问题。这是简化的代码(请注意,我尝试使用以下方法解决此问题 header 像往常一样,但仍然有问题 - 我在此代码片段中省略了它们):
#include <iostream>
#include <memory>
using namespace std;
class Context
{
public:
friend class State;
Context() { }
private:
State* m_state;
};
class State
{
public:
State() { }
virtual void Trigger1() = 0;
virtual void Trigger2() = 0;
};
class LLT : public State
{
public:
LLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class ALL : public State
{
public:
ALL() { }
void Trigger1() { new LLT(); }
void Trigger2() { new DH(); }
};
// DL needs to 'know' about DH.
class DL : public State
{
public:
DL() { }
void Trigger1() { new ALL(); }
void Trigger2() { new DH(); }
};
class HLT : public State
{
public:
HLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class AHL : public State
{
public:
AHL() { }
void Trigger1() { new DH(); }
void Trigger2() { new HLT(); }
};
// DH needs to 'know' about DL.
class DH : public State
{
public:
DH () { }
void Trigger1() { new AHL(); }
void Trigger2() { new DL(); }
};
int main()
{
auto_ptr<LLT> llt (new LLT);
auto_ptr<ALL> all (new ALL);
auto_ptr<DL> dl (new DL);
auto_ptr<HLT> hlt (new HLT);
auto_ptr<AHL> ahl (new AHL);
auto_ptr<DH> dh (new DH);
return 0;
}
问题基本上是在状态模式中,状态转换是通过 调用 Context 类中的 ChangeState 方法,该方法调用 下一个状态的构造函数。
由于循环依赖,我无法调用构造函数,因为它是 不可能预先定义“问题”状态的两个构造函数。
我查看了this文章,模板方法似乎是理想的解决方案 - 但它无法编译,而且我对模板的了解相当有限......
我的另一个想法是尝试向子类状态引入一个 Helper 类, 通过多重继承,看看是否可以指定基类的构造函数 并引用状态子类的构造函数。但我认为那是相当 雄心勃勃...
最后,直接实现工厂方法设计模式是否是最好的方法 解决整个问题?
最佳答案
您可以在类定义之外定义成员函数,例如
class DL : public State
{
public:
void Trigger2();
};
inline void DL::Trigger2() { new DH(); }
定义依赖于这些类定义之后的类定义的成员函数。这些类被定义之后。仅当您在头文件中定义类的成员函数外部时,inline
关键字才是必需的。
顺便说一句,为什么你只在函数中使用 new DH()
?你到处都在泄漏内存!
关于c++ - 解决涉及 C++ 状态机的前向声明问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3045483/