允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
简单例子 电灯 A——B——C——A
- 上下文Context
Light类
class Light {offLightState = new OffLightState(this); // 持有状态对象的引用weakLIghtState = new WeakLIghtState(this);strongLightState = new StrongLightState(this);button = null;init() {var button = document.createElement('button');this.button = document.body.appendChild(button);this.button.innerHTML = '开关';this.currState = this.offLightState;this.button.onClick = () => {this.currState.buttonWasPressed(); // 委托给状态类}}setState(state) {this.currState = state;}}
- 状态类
关闭、弱光、强光
interface LightState {buttonWasPressed: () => void}class OffLightState implements LightState {constructor(private light) {}buttonWasPressed() {console.log('弱光'); // 行为this.light.setState(this.light) ; // 改变内部状态}}
