<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>状态模式</title></head><body> <script> // 状态父类 class LightState { constructor(light) { this.light = light } buttonWasPressed() { throw new Error('父类的buttonWasPressed办法必须被重写') } } // 状态子类 class OffLightState extends LightState { buttonWasPressed() { console.log('弱光') // offLightState对应的行为 this.light.setState(this.light.weakLightState) // 切换状态到 weakLightState } } class WeakLightState extends LightState { buttonWasPressed() { console.log('强光') // weakLightState对应的行为 this.light.setState(this.light.strongLightState) // 切换状态到 strongLightState } } class StrongLightState extends LightState { buttonWasPressed() { console.log('超强光') // strongLightState对应的行为 this.light.setState(this.light.superStrongLightState) // 切换状态到 superStrongLightState } } class SuperStrongLightState extends LightState { buttonWasPressed() { console.log('关灯') // superStrongLightState对应的行为 this.light.setState(this.light.offLightState) // 切换状态到 offLightState } } // 灯类 class Light { constructor() { this.offLightState = new OffLightState(this) this.weakLightState = new WeakLightState(this) this.strongLightState = new StrongLightState(this) this.superStrongLightState = new SuperStrongLightState(this) this.button = null } init() { const button = document.createElement('button') this.button = document.body.appendChild(button) this.button.innerHTML = '开关' this.currState = this.offLightState // 设置以后状态 this.button.onclick = () => this.currState.buttonWasPressed() // 将申请委托给以后的状态对象 } setState(newState) { this.currState = newState } } const light = new Light() light.init() </script></body></html>