声明:本博文篇幅短,适合review。
一、概念
当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。状态模式主要解决的是当控制一个对象状态的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。
二、模式结构图
class Context;
class State
{
public:
virtual void handle(Context * context) = 0;
};
class ConcreteStateA : public State
{
public:
void handle(Context * context){
cout<<"current State : A Next : B"<<endl;
context->setState(new ConcreteStateB());
}
};
class ConcreteStateB : public State
{
public:
void handle(Context * context){
cout<<"current State : B Next : A"<<endl;
context->setState(new ConcreteStateA());
}
};
class Context
{
public:
Context(State * state){
mState = state;
}
State * getState(){
return mState;
}
void setState(State * state){
delete mState;
mState = state;
}
void request(){
mState->handle(this);
}
private:
State * mState;
};
void main(){
Context * context = new Context(new ConcreteStateA());
context->request();
context->request();
}
三、例子
class DressClothes;
class SeasonState
{
public:
virtual void dressClothes(DressClothes * dc) = 0;
};
class SpringState : public SeasonState
{
public:
void dressClothes(DressClothes * dc){
cout<<"春天来了,我穿保暖衣和薄外套就可以了"<<endl;
dc->setState(new SummerState());
}
};
class SummerState : public SeasonState
{
public:
void dressClothes(DressClothes * dc){
cout<<"夏天真热,我只穿一件薄T-恤"<<endl;
dc->setState(new AutumnState());
}
};
class AutumnState : public SeasonState
{
public:
void dressClothes(DressClothes * dc){
cout<<"秋天终于来了,我可以穿皮夹克了"<<endl;
dc->setState(new WinterState());
}
};
class WinterState : public SeasonState
{
public:
void dressClothes(DressClothes * dc){
cout<<"冬天好冷,我要穿棉袄"<<endl;
dc->setState(new SpringState());
}
};
class DressClothes
{
public:
DressClothes(SeasonState * state){
mState = state;
}
State * getState(){
return mState;
}
void setState(SeasonState * state){
delete mState;
mState = state;
}
void dress(){
mState->dressClothes(this);
}
private:
State * mState;
};
void main(){
DressClothes * dc = new DressClothes(new SpringState());
dc->dress();
dc->dress();
}
四、优缺点
1、优点
a、它将与特定状态相关的行为局部化,并且将不同状态的行为分割开来
b、可以让多个环境对象共享一个状态对象,从而减少系统中对象的个数
c、避免大量和状态相关的条件判断语句的编写
d、增加新的状态和转换比较容易
2、缺点
a、状态模式的使用必然会增加系统类和对象的个数。
b、对开闭原则支持不好。
c、如果使用不当将导致程序结构和代码的混乱。