// 改写Light类 var Light = function () { this.offLightState = new OffLightState(this) this.weakLightState = new WeakLightState(this) this.strongLightState = new StrongLightState(this) this.button = null }
Light.prototype.init = function () { var button = document.createElement('button') var self = this button.innerHTML = '开关' this.currState = this.offLightState this.button = document.body.appendChild(button) this.button.onclick = function () { self.currState.buttonWasPressed() } }
Light.prototype.setState = function (newState) { this.currState = newState }
// 改写Light类 var Light = function () { this.offLightState = new OffLightState(this) this.weakLightState = new WeakLightState(this) this.strongLightState = new StrongLightState(this) this.superStrongLightState = new SuperStrongLightState(this) this.button = null }
▼使用抽象类定义状态类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var State = function () {}
State.prototype.buttonWasPressed = function () { thrownewError('父类的buttonWasPressed方法必须被重写') }
var SuperStrongLightState = function (light) { this.light = light }
SuperStrongLightState.prototype = new State()
SuperStrongLightState.prototype.buttonWasPressed = function () { console.log('关灯') this.light.setState(this.light.offLightState) // 状态切换到offLightState }