1 primary Electric Lamp example, state is only represented by a string and not encapsulated to an object
classlight{Constructor () { This. State ='off'; Let button= Document.createelement ('Button' ); Button.innerhtml='Switch'; This. Button =document.body.appendChild (button); This. Button.onclick = () ={ This. buttonwaspressed (); }} buttonwaspressed () {if( This. state = = ='off') {Console.log ('turn on the light' ); This. State =' on'; }Else if( This. state = = =' on') {Console.log ('Turn off the lights' ); This. State ='off'; } }}NewLight ();
state mode----Object-oriented version
The key to implementation
1 State with object representation
2 The behavior of the state is abstracted into a unified method (buttonwaspressed), which can implement the delegate. This behavior can be placed in the State class, or in the context,
3 The state internally modifies the current state, (that is, what the next state is, and is already clear within each State object)
4 when the triggering action starts, the behavior of the current state is invoked with the current state, thus successfully avoiding the use of an ugly if Else branch.
1 class state{2 buttonwaspressed () {3 Throw NewError (' buttonwaspressed method of parent class must be overridden ' )4 }5 }6 7 class Stronglightstate extends state{8 Constructor (light) {9 super ();Ten This. Light = Light One } A //buttonwaspressed () { - //Console.log ('-off light '); - //this.light.setState (this.light.offLightState) the // } - } - - class Offlightstate extends state{ + Constructor (light) { - super (); + This. Light = Light A } at buttonwaspressed () { -Console.log ('--and weak light ')); - This. Light.setstate ( This. Light.weaklightstate) - } - } - in class Weaklightstate extends state{ - Constructor (light) { to super (); + This. Light = Light - } the buttonwaspressed () { *Console.log ('--and strong light ')); $ This. Light.setstate ( This. Light.stronglightstate)Panax Notoginseng } - } the + class light{ A Constructor () { the This. stronglightstate =NewStronglightstate ( This); + This. offlightstate =NewOfflightstate ( This); - This. weaklightstate =NewWeaklightstate ( This); $ This. currstate = This. offlightstate;//set the current state $ -Let button = document.createelement (' button ' ); -button.innerhtml = ' switch '; the This. Button =document.body.appendChild (button); - This. Button.onclick = () ={Wuyi This. currstate.buttonwaspressed (); the } - } Wu - setState (newstate) { About This. currstate =newstate $ } -}
State mode full resolution--JAVASCRIPT