当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同的一系列类当中,可以把复杂的逻辑判断简单化。
代码
#include <iostream>
using namespace std;
class Light;
class State{ //状态
public:
virtual void pressSwitch(Light * light) = 0;
};
class Light{ //电灯
public:
Light( State *sta):state(sta){}
void pressSwitch(){
state->pressSwitch(this);
}
void setState(State *s){state = s;}
private:
State *state;
};
class OffState:public State{ //关着的状态
void pressSwitch(Light * light);
};
class OnState:public State{ //开着的状态
public:
void pressSwitch(Light * light) {
cout<<"pressSwitch to off"<<endl;
light->setState(new OffState);
}
};
void OffState::pressSwitch(Light * light) {
cout<<"pressSwitch to on"<<endl;
light->setState(new OnState());
}
使用
int main(){
Light *l = new Light(new OffState);
l->pressSwitch();
l->pressSwitch();
return 1;
}
结果
pressSwitch to on
pressSwitch to off