"javascript Design Pattern sheet" Collation

Source: Internet
Author: User

A new book on design patterns, the JavaScript design model, is being studied recently, and more design patterns are described in this Book.

first, the creation of design patterns

Includes simple factories, factory methods, abstract factories, builders, prototypes, and Singleton patterns.

1) Simple Factory

Also called the static factory method, a factory object determines the creation of an instance of a Product object class.

The first is to create a class instantiation object, and the second is to create a new object and then wrap it to enhance its properties and Functionality.

Demo Code.

2) Factory method

by abstracting the product class, the business is primarily responsible for creating instances of Multi-Class Products.

Treat a factory method as a factory class that instantiates an Object.

Demo Code.

3) Abstract Factory

The factory abstraction of a class enables its business to be used to create a product class cluster, without being responsible for creating instances of a particular class of Products.

Use it as the parent class to create some Subclasses.

Demo Code.

4) Builders

Separating the building layer of a complex object from its presentation layer allows for different representations of the same build Process.

It is more concerned with the whole process of creating this object, or even creating the details of the Object.

Demo Code.

5) prototype mode

Use a prototype instance to point to the class that created the object, and the class that is used to create the new object shares the properties and methods of the prototype Object.

The prototype pattern is a reusable, shareable, time-consuming extraction from a base class, and in its prototype, subclasses inherit methods and properties by combining inheritance or parasitic inheritance.

Demo Code.

6) Single case mode

An object class that is only allowed to instantiate Once. Sometimes we also use an object to plan a namespace, organize the properties and methods on the Object.

Demo Code.

second, Structural design mode

1) appearance mode

Provides a more advanced unified interface for a complex set of subsystem interfaces, which makes access to subsystem interfaces Easier.

In js, it is sometimes used to encapsulate the underlying structure compatibility to simplify user Use.

Demo Code.

2) Adapter Mode

The interface (method or Property) of a class (object) is transformed into another interface, which satisfies the user's requirements and causes incompatibilities between the interfaces of the class (object) to be resolved through the Adapter.

Adaptable to heterogeneous frameworks, parameter adapters, and Data.

Dmeo Code.

3) Proxy Mode

Because an object cannot directly reference another object, a proxy object is required to mediate between the two Objects.

Webmaster statistics, JSONP, Proxy Template.

4) Decorator Mode

On the basis of not changing the original object, the original object can satisfy the more complicated requirement by wrapping the extension (adding attribute or method).

Demo Code.

5) Bridging mode

While the system changes along multiple latitudes, it does not increase its complexity and has achieved decoupling.

Extract similarities, events and business logic between the bridge and the diversified Object.

Decoupling the implementation layer (such as an element's binding event) from the abstraction layer (such as the decorated page UI Logic) so that the two parts can change independently.

Demo Code.

6) Combination Mode

Also called Partial-overall mode, which combines objects into a tree structure to represent the hierarchical structure of "partial whole".

The combined mode makes the user consistent with the use of individual objects and composite objects.

Composite object classes behave in a more consistent manner by inheriting the same parent class so that they have a uniform method.

Demo Code.

7) enjoy meta mode

The use of sharing technology to effectively support a large number of fine-grained objects, to avoid having the same content between objects causing unnecessary overhead.

Enjoy meta-objects, and enjoy Meta-action. Extract common methods and data to improve page Efficiency.

Demo Code.

third, Behavioral Design Patterns

1) Template Method Mode

A set of operation algorithm skeletons is defined in the parent class, and some implementation steps are deferred to subclasses so that subclasses can redefine the implementation of some steps in the algorithm while not altering the parent Class's structure ALGORITHM.

The Cue box is Normalized.

2) Observer mode

Also known as the Publish-subscribe mode or message mechanism, a dependency relationship is defined, which solves the coupling between the principal object and the Observer's Function.

The biggest effect is to solve the coupling between classes or objects, resolving two interdependent objects, making them dependent on the Observer's message Mechanism.

Demo Code.

3) State mode

When an object's internal state changes, It causes its behavior to change, which looks like it has changed the Object.

The state mode is not only the problem of the bloated branch judgment in the program, but the transformation of each branch into a state independent, which facilitates the management of each state without traversing all the branches each time it executes.

Demo Code.

4) Policy mode

Encapsulates a defined set of algorithms so that they can be replaced with each other. The encapsulated algorithm has some independence and will not change with the Client.

The strategy mode makes the algorithm independent of the module logic and allows us to concentrate on the development of the algorithm without being constrained by the logic of the Module.

There are currently 3 ways to optimize branch statements, factory methods, State patterns, and policy patterns.

5) Responsibility Chain Mode

The coupling between the sender of the request and the recipient of the request is resolved, and the request process is decomposed through multiple objects on the chain of responsibility, enabling the request to be passed between multiple objects until the last object finishes processing the Request.

Decomposition requirements, The decomposition of everything into a module object processing, the requirements are decomposed into separate parts, division of labor only do their own things, unrelated things to the next object, until the Completion.

Request Module = = "response data adapter module = =" To create a component module = = "unit Test

6) Command mode

The logic of creating the module is encapsulated in an object that provides a parameterized request interface by invoking this interface and passing parameters to implement some of the methods inside the Object.

Encapsulation functionality that provides a simple and efficient API to resolve the coupling between the initiator of the command and the executor of the Command.

Demo Code.

7) Visitor Mode

For elements in an object structure, defines a new way to access elements in the structure without changing the Object.

8) Broker Mode

Encapsulates the interaction between a series of objects through a mediator object, so that objects are no longer referenced to each other, reducing the coupling between them.

The subscribers in the Observer pattern are mutual, and the broker pattern subscribers are one-way, the message is uniformly published by the mediator object, and all subscribers are indirectly managed by the Intermediary.

9) Memo Mode

Without destroying the encapsulation of an object, the state inside the object is captured and saved outside the object for later use by the object, or the object recovery reverts to a previous State.

Caching data, The M part of mvc, often caches some Data.

10) iterator mode

The elements inside the aggregation object can be accessed sequentially, without exposing the inner structure of the Object.

Iterators are a feasible scheme for optimizing circular statements, which makes the program clear and easy to read, and solves the coupling between the Object's user and the Object's internal Structure.

Demo Code.

four, the skill type design pattern

1) Delegate Mode

Multiple objects receive and process the same request, and they delegate requests to another object to process the request Uniformly.

Delegate the parent element, predict the future, and distribute the Data.

Demo Code.

2) Throttle Mode

Throttle control of repetitive operations, perform the last operation and cancel other operations to improve performance.

throttle, picture delay loading, Statistical packaging.

3) Simple Stencil Mode

The view is pieced together by formatting strings to avoid a large number of node operations when creating Views.

Using regular matching to format string performance is much higher than the performance of stitching view Execution.

Includes three parts: string template library, format method, string concatenation Operation.

Demo Code.

4) Lazy Mode

Reduce the repetitive branch judgment of each code execution by masking the branch in the original object by redefining the Object.

The lazy mode is divided into two types: the first file is executed immediately after the object method is redefined, and the second is redefined when the method object is used for the first Time.

Demo Code.

5) Participant Mode

Executes the given function in a specific scope and passes the parameters Intact.

The participant pattern is the crystallization of two techniques, function binding and function curry.

Demo Code.

6) Waiting mode

Trigger future actions by listening to multiple asynchronous processes.

The wait mode is intended to handle lengthy operations, timer operations, asynchronous operations, and More.

The Listener object is buried in the time-consuming operation, changing the state of the listener object at some point, when all listener objects are completed, the completion callback is executed, and if one is interrupted, an interrupt callback is Executed.

Demo Code.

five, Architectural design mode

1) Synchronization Module

After the request is issued, regardless of the existence of the module, immediately follow-up logic to implement module development in the immediate use of the Module.

Demo Code.

2) Asynchronous Module

AMD, after the request is made, continue with other business logic until the module is loaded and execute the subsequent logic, implementing module development in the module after the completion of the REFERENCE.

3) MVC

Organize your schema code in a way that separates business logic, data, and Views.

When you create an interface in the view layer, the data in the model layer is used to couple the two layers Together. Reduces the flexibility and reusability of view Creation.

Demo Code.

4) MVP

The view layer does not directly refer to the data of the model layer, but realizes the data access to the model layer through the presenter Layer.

All levels of interaction occur in the presenter layer, which solves the coupling between the view layer and the model Layer.

however, The view layer is not independent enough to create a view that is controlled by presenter.

Demo Code.

5) MVVM

Tailor a set of ViewMode layers for the view layer and create properties and methods in ViewMode to bind the data of the model layer to the view layer and Interact.

A viewmode can correspond to multiple view layers or model layers, and the code in the ViewMode becomes highly reusable.

View Layer independent development, so that those who do not understand js, just understand the HTML content and follow the View layer specification format, Create a view, you can complete a complex page Development.

"javascript Design Pattern sheet" Collation

Related Article

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.