意图
允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
应用场景
uu
类图
参与者
- Context
定义客户感兴趣的接口
维护一个ConcreteState子类的实例,这个实例定义当前状态 - State(状态)
定义一个接口以封装与Context的一个特定状态相关的行为 - ConcreteState
每一个具体类实现一个与Context的一个状态相关的行为
代码
//有错误,c++不能在同一个文件中定义相互引用的类
#
include
<iostream
>
using namespace std;
//抽象状态类,定义一个接口,
//用来封装与Context的特定状态相关的行为
class State
{
public :
virtual void Handle(Context *pContext) = 0;
};
class ConcreteStateA : public State
{
public :
void Handle(Context *pContext)
{
//设置ConcreteStateA的下一个状态是ConcreteStateB
pContext - >SetState( new ConcreteStateB());
}
};
class ConcreteStateB : public State
{
public :
void Handle(Context *pContext)
{
//设置ConcreteStateB的下一个状态是ConcreteStateA
pContext - >SetState( new ConcreteStateA());
}
};
//Context类:维护一个ConcreteState子类的实例,
//这个实例定义当前的状态
class Context
{
private :
State *pState;
public :
Context(State *pState)
{
this - >pState = pState;
}
void SetState(State *pState)
{
this - >pState = pState;
}
void Request()
{
pState - >Handle( this);
}
};
int main()
{
Context *pContext = new Context( new ConcreteStateA());
//不断请求,更换状态
pContext - >Request();
pContext - >Request();
pContext - >Request();
pContext - >Request();
}
using namespace std;
//抽象状态类,定义一个接口,
//用来封装与Context的特定状态相关的行为
class State
{
public :
virtual void Handle(Context *pContext) = 0;
};
class ConcreteStateA : public State
{
public :
void Handle(Context *pContext)
{
//设置ConcreteStateA的下一个状态是ConcreteStateB
pContext - >SetState( new ConcreteStateB());
}
};
class ConcreteStateB : public State
{
public :
void Handle(Context *pContext)
{
//设置ConcreteStateB的下一个状态是ConcreteStateA
pContext - >SetState( new ConcreteStateA());
}
};
//Context类:维护一个ConcreteState子类的实例,
//这个实例定义当前的状态
class Context
{
private :
State *pState;
public :
Context(State *pState)
{
this - >pState = pState;
}
void SetState(State *pState)
{
this - >pState = pState;
}
void Request()
{
pState - >Handle( this);
}
};
int main()
{
Context *pContext = new Context( new ConcreteStateA());
//不断请求,更换状态
pContext - >Request();
pContext - >Request();
pContext - >Request();
pContext - >Request();
}