#pragma once
#include "stdafx.h"
#include <queue>
#include<iostream>
using namespace std;
//设计模式-状态模式State
/*
当一个对象的内在状态改变时,允许改变其行为,这个对象看起来就是改变了类。
*/
class CContexct;
class CState {//抽象状态类,定义一个接口以封装与Context的一个特定状态相关的行为。
public:
virtual void Handle(CContexct *pContext) = 0;
};
class CContexct {//维护一个concretestate子类的实例,这个实例定义当前的状态。
private:
CState *m_pState;
queue<CState *>m_qHashMemory;
public:
CContexct(CState *pState) {
while (!m_qHashMemory.empty()) {
m_qHashMemory.pop();
}
m_pState = pState;
m_qHashMemory.push(m_pState);
}
~CContexct() {
while (!m_qHashMemory.empty()) {
delete m_qHashMemory.front();
m_qHashMemory.pop();
}
}
void SetContext(CState *pState) {
m_pState = pState;
m_qHashMemory.push(m_pState);
}
void Request() {
m_pState->Handle(this);
}
};
class CConcreteStateC :public CState {//具体状态,每一个子类实现一个与Context的一个状态相关的行为。
public:
void Handle(CContexct *pContext) {
cout << "over" << endl;
return;
}
};
class CConcreteStateB : public CState {
public:
void Handle(CContexct *pContext) {
pContext->SetContext(new CConcreteStateC());
pContext->Request();
}
};
class CConcreteStateA : public CState {
public:
void Handle(CContexct *pContext) {
pContext->SetContext(new CConcreteStateB());
pContext->Request();
}
};
int main() {
CContexct *pContexct = new CContexct(new CConcreteStateA());
pContexct->Request();
delete pContexct;
getchar();
return 0;
}