Qt C++ State模式

我们在做多个条件判断的时候常会用到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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值