状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑化。
模式实现:
class Context;
class State{
public:
virtual void Handle(Context *pContext) = 0;
};
class ConcreteStateA: public State{
public:
virtual void Handle(Context *pContext){
std::cout << "I'm concretestateA.\n";
}
};
class ConcreteStateB: public State{
public:
virtual void Handle(Context *pContext){
std::cout << "I'm concretestateB.\n";
}
};
class Context{
public:
Context(State *state):pState(state){}
void Request(){
if(pState){
pState->Handle(this);
}
}
void ChangeState(State *pstate){
pState = pstate;
}
private:
State *pState;
};
客户端
int main(){
State *pState = new ConcreteStateA();
Context *context = new Context(pState);
context->Request(); //Output: I'm concretestateA.
State *pState2 = new ConcreteStateB();
context->ChangeState(pState2);
context->Request(); //Output: I'm concretestateB.
if(pState){
delete pState;
pState = NULL;
}
if(pState2){
delete pState2;
pState2 = NULL;
}
if(context){
delete context;
context = NULL;
}
return 0;
}