Concept and Usage Analysis of JS design patterns, and js Design Patterns
This article describes the concept and usage of the state mode in JS design mode. We will share this with you for your reference. The details are as follows:
1. Overview
When the internal state of an object changes, it is allowed to change its behavior. This object seems to have changed its class.
2. Solved problems
The main solution is when the conditional expressions that control the state transition of an object are too complex. Transferring the State judgment logic to a series of classes that indicate different states can simplify complicated logic judgment.
Function Context (_ state) {this. state = _ state; this. request = function () {this. state. handle (this) ;}} function ConcreteStateA () {this. handle = function (context) {console. log ("A"); context. state = new ConcreteStateB () ;}} function ConcreteStateB () {this. handle = function (context) {console. log ("B"); context. state = new ConcreteStateA () ;}// set the initial state of Context to ConcreteStateAvar context = new Context (new ConcreteStateA (); // continuously requests, change the status context at the same time. request (); context. request ();
The usage scenarios of the Status mode are also specific, including the following:
The behavior of an object depends on its state, and it must change its behavior according to its state at runtime.
An operation contains a large number of branch statements, and these branch statements depend on the state of the object. The status is usually expressed by one or more enumerated constants.
Application scenarios:
A call can be in the following statuses: obtaining the phone number, dialing, calling, and calling.
These statuses are performed in the order of times, so we can implement the state mode based on these statuses;
Get phone number
Dialing
On call
Call ended
Constantly call this methodcontext.request();
To determine the current status;