state.h
#ifndef STATE_H
#define STATE_H
#include <QtDebug>
#include "context.h"
class Context;
class State
{
public:
State() {}
virtual void doAction()=0;
};
class StartState : public State
{
public:
StartState (Context *context) {this->context=context;}
void doAction();
private:
Context *context;
};
class StopState : public State
{
public:
StopState(Context *context){this->context=context;}
void doAction();
private:
Context *context;
};
#endif // STATE_H
context.h
#ifndef CONTEXT_H
#define CONTEXT_H
#include "state.h"
class Context
{
public:
Context()
{
m_start = new StartState(this);
m_stop = new StopState(this);
m_state = m_start;
}
void setState(State *state)
{
m_state = state;
}
State *getStart()
{
return m_start;
}
State *getStop()
{
return m_stop;
}
void doAction()
{
m_state->doAction();
}
private:
State *m_start,*m_stop,*m_state;
};
void StartState::doAction()
{
qDebug() << "关闭";
this->context->setState(this->context->getStop());
}
void StopState::doAction()
{
qDebug() << "开始";
this->context->setState(this->context->getStart());
}
#endif // CONTEXT_H
main.cpp
#include <QApplication>
#include <QtDebug>
#include "context.h"
#include "state.h"
//状态模式
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Context *context=new Context();
context->doAction();
context->doAction();
context->doAction();
context->doAction();
return a.exec();
}
输出结果
关闭
开始
关闭
开始
上述代码还有C++的特色,各个具体状态中,所对应转换状态方法,只能在类外实现,而不能在直接在StartState 与StopState里面实现。因为C++不像java,Java编译的时候一次性把所有东西读进去。C++是见一行读一行。这里Context类用到State,StartState 与StopState用到了Context,类间相互调用在C++中是不行的。
参考:https://blog.csdn.net/yongh701/article/details/49154439
UML