js several common design patterns

A. Singleton

Singleton also known as list mode, also called for more monomers mode. Software design is simple but the most commonly used design patterns. In JavaScript, there is achieved a single example of a wide variety of ways, the simplest way is to use the object in a literal way, which can contain a literal large number of properties and methods.

 

To extend the object can add their own private members and methods, and then using these variables and closure package function declaration inside. Sample code is as follows:

 

 

Second, the factory pattern

Factory pattern is determined by a method which in the end instance of the class to be created, and these instances often have the same interface. This mode is mainly used in the examples of the type can not be determined at compile time, but in the case of performing the decision. 

Example:

 

 

This code instructions from es5 of new and constructor, new copy and rewriting process itself is only an object, and specifically what will be generated when a call is passed into ObjectFactory parameters of the decision.

Third, the adaptation mode

The main mode of adaptation solutions to solve some of incompatible interfaces generated. Adapters can provide the user with a unified without modifying these interfaces are not compatible case glossed over in adapter. On the surface of the facade before and they feel more like a model, are subject to other interfaces or re-packaging presentation, and the adapter mode bias is to resolve compatibility issues, the facade pattern is biased convenience principle.

For example, a simple way to query student academic achievement:

 

 

It is about a form compatible adapter to handle the parameters area. Very simple adapter mode sense - adapting, solving compatibility issues.

Examples of two: jquery inside of $ $ id selectors need to change in order to match the project and will be converted into $ $ id very relaxed. as follows:

 

Fourth, the appearance mode

Appearance pattern, is a relatively simple and ubiquitous mode. Facade pattern provides a high-level interface that makes the client easier to call or subsystems. Simple enough code to indicate a paragraph:

 

Guess you like

Origin www.cnblogs.com/sweeeper/p/11711533.html