使用QT新建Widget工程。
widget.h如下:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QDebug>
class Context;
class State {
public: virtual void doAction(Context* context)=0;
public: virtual void toString()=0;
public: virtual ~State();
};
class Context {
private: State* m_state;
public: Context();
void SetState(State* state);
State* GetState(void);
};
class StartState : public State {
public : StartState();
virtual void toString();
virtual void doAction(Context* context);
virtual ~StartState();
};
class StopState : public State {
public : StopState();
virtual void toString();
virtual void doAction(Context* context);
virtual ~StopState();
};
#endif // WIDGET_H
widget.cpp如下:
#include "widget.h"
State::~State() { }
StartState::StartState() { }
StartState::~StartState() { }
StopState::StopState() { }
StopState::~StopState() { }
void StartState::toString() {
qDebug()<<"StartState toString";
}
void StartState::doAction(Context *context) {
qDebug()<<"StartState doAction";
context->SetState(this);
}
void StopState::toString() {
qDebug()<<"StopState toString";
}
void StopState::doAction(Context *context) {
qDebug()<<"StopState doAction";
context->SetState(this);
}
Context::Context() {
m_state = nullptr;
}
void Context::SetState(State* state) {
m_state = state;
}
State* Context::GetState() {
return m_state;
}
main.cpp如下:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Context* context = new Context();
StartState* start = new StartState();
start->doAction(context);
context->GetState()->toString();
StopState* stop = new StopState();
stop->doAction(context);
context->GetState()->toString();
return a.exec();
}
运行结果如下:
说明:状态模式适合用于状态机、流程控制,可以替代if else。但是一个状态就是一个类,状态太多时,不适用。