我们在做多个条件判断的时候常会用到switch,如果条件和内容过于繁琐,内容庞大的话,state模式就十分有用了。
state.h
#pragma once
#include <QDebug>
class CState;
class CContext
{
public:
CContext(CState* state):m_state(state){}
~CContext();
void request();
void changeState(CState* state);
private:
CState* m_state;
};
class CState
{
public:
virtual void Handle(CContext *context) = 0;
};
class CConcreateStateA : public CState
{
public:
CConcreateStateA(){qDebug() << "this stateA!";}
public:
void Handle(CContext *context);
};
class CConcreateStateB : public CState
{
public:
CConcreateStateB(){qDebug() << "this stateB!";}
public:
void Handle(CContext *context);
};
state.cpp
#include "state.h"
CContext::~CContext()
{
delete m_state;
}
void CContext::request()
{
if (m_state)
{
m_state->Handle(this);
}
}
void CContext::changeState(CState* state)
{
if (m_state)
{
delete m_state;
m_state = 0;
}
m_state = state;
}
void CConcreateStateA::Handle(CContext *context)
{
if (context)
{
context->changeState(new CConcreateStateB);
}
}
void CConcreateStateB::Handle(CContext *context)
{
if (context)
{
context->changeState(new CConcreateStateA);
}
}
main.cpp
#include <QApplication>
#include "state.h"
int main(int argc,char **argv)
{
QApplication app(argc,argv);
CConcreateStateA *stateA = new CConcreateStateA;
CContext *context = new CContext(stateA);
context->request();
context->request();
context->request();
delete context;
return app.exec();
}