Concept and Usage Analysis of JS design patterns, and js Design Patterns

Source: Internet
Author: User

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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.