目的:允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
解决问题:对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。
何时使用:代码中包含大量与对象状态有关的条件语句。
例子:
有一个台灯,它有3个按钮,分别对应关灯(off),强光(strong),弱光(weak)。当按钮切换的时候,分别对应不同状态的行为。
首先,定义灯状态类的接口:
interface LightContent { //灯状态类的接口
action(content: Light);
}
接着定义灯的三个状态类:
class OffState implements LightContent { //关灯的状态类
public action(content: Light) {
content.setState(this); // 设置当前灯的状态
}
public ownMethod() {
console.log('当前是关灯'); //当前灯状态下的行为
}
}
class StrongState implements LightContent { //强光的状态类
public action(content: Light) {
content.setState(this); // 设置当前灯的状态
}
public ownMethod() {
console.log('当前是强光'); //当前灯状态下的行为
}
}
class WeakState implements LightContent { //弱光的状态类
public action(content: Light) {
content.setState(this); // 设置当前灯的状态
}
public ownMethod() {
console.log('当前是弱光'); //当前灯状态下的行为
}
}
定义灯类:
class Light { //灯类
public lightState: LightContent; //灯的状态类
public setState(lightState: LightContent) {
this.lightState = lightState;
}
}
运行:
private light = new Light();
public onOffClick() { //关灯
const off = new OffState();
off.action(this.light);
off.ownMethod();
}
public onStrongClick() { //强光
const strong = new StrongState();
strong.action(this.light);
strong.ownMethod();
}
public onWeakClick() { //弱光
const weak = new WeakState();
weak.action(this.light);
weak.ownMethod();
}
当实例化完状态类之后,调用action函数之后,灯类的状态就改变了,就可以使用当前状态类的方法(ownMethod)了。
用状态模式这样写,在增加其他状态时,就不用修改Light类,只写相应的状态类就可以了。
如果不用状态模式,用if else,增加状态时,就要增加ifelse判断,修改Light类,这样增加了代码耦合性,不利于阅读和管理代码。