Qt C++ State模式
来源:互联网 发布:美图秀秀叠图软件 编辑:程序博客网 时间:2024/05/21 09:50
我们在做多个条件判断的时候常会用到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();
}
- Qt C++ State模式
- C++state模式技术,无止境
- state模式
- State模式
- State模式
- state模式
- State模式
- State 模式
- State 模式
- state模式
- state模式
- State 模式
- State模式
- State模式
- State模式
- State 模式
- state模式
- State模式
- android 代码方式注册广播接收着
- nginx slab算法
- 做SDK A2版rootfs
- OpenCV:VideoCapture类
- P2P之UDP穿透NAT的原理与实现 [转]
- Qt C++ State模式
- android 点击textView 访问网络
- linux内核时钟机制及延时
- 用telnet来测试你自己写的TCP服务器
- Redis以及Redis的php扩展安装
- android 获取手机运营商
- hibernate学习笔记二
- 一周讨论精华
- android findView 如何避免类型转换