将每个状态封装成类,通过场景进行映射相关的状态类,从而实现状态模式
下面制作一个关于灯光的场景,灯光按钮有三种状态,按每一个按钮,都会触发一个信号,并把下一个状态传递给下一个类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 abstract class LightState{ abstract state:string ; light:Light; constructor (light:Light ){ this .light = light; } print(){ console .log(this .state); } abstract changeState():void ; } class OffLightState extends LightState{ state:string = 'off' ; constructor (light:Light ){ super (light); } changeState(){ this .light.setState(this .light.weakState); } } class WeakLightState extends LightState{ state:string = 'weak' ; constructor (light:Light ){ super (light); } changeState(){ this .light.setState(this .light.strongState); } } class StrongLightState extends LightState{ state:string = 'strong' ; constructor (light:Light ){ super (light); } changeState(){ this .light.setState(this .light.offLightState); } } class Light{ offLightState:OffLightState = new OffLightState(this ); weakState:WeakLightState = new WeakLightState(this ); strongState:StrongLightState = new StrongLightState(this ); currentState:LightState = this .offLightState; setState(newState:LightState){ this .currentState = newState; } onPress(){ this .currentState.print(); this .currentState.changeState(); } } let light = new Light();light.onPress(); light.onPress(); light.onPress();