Front End Learning Summary (14) JavaScript design pattern

Source: Internet
Author: User
Tags event listener

What is a design pattern?

Design patterns are a set of reusable, most known, categorized purposes, Code design experience Summary . Design patterns are used in order to reuse code, make code easier for others to understand , and ensure code reliability.

Two design principles

To learn the design pattern, we must first understand the design principle that the design pattern relies on:

(1) Single duty principle (SRP principle): An object (method) Only one thing to do.
Use of the design mode: Agent mode, singleton mode, decorator mode.

(2) Minimum knowledge principle (Lkp principle): A software entity should interact with other entities as little as possible. Software entities are a generalized concept that includes not only objects, but also systems, classes, modules, functions, variables, and so on.
The principle of least knowledge requires that when designing a program, we should minimize the interaction between objects, and one object should know as little as possible about other objects.

Application of Design Patterns: Intermediary mode, appearance mode, etc.

(3) Opening and closing principle (open-closed principle/OCP principle): Software entities (classes, modules, functions) should be extensible, but not modifiable.

Application of Design mode: publish-subscribe mode, template method mode, strategy mode, proxy mode, responsibility chain mode, etc.

(4) on the Richter scale conversion principle: Subclass inherits the parent class, the individual falls completely can

(5) Dependency reversal principle: Refers to an object, if it has the underlying object, directly invoke the underlying.

(6) Synthesis/aggregation Reuse principle: new objects should use as many existing objects as possible to make them part of new objects

(7) interface isolation principle. Customers should not be forced to rely on interfaces that are not used. One problem is that there is no explicit interface in JS, but we have a way around.

Solid design Principles Please refer to: http://www.infoq.com/cn/news/2014/01/solid-principles-javascript

Three common design patterns

(1) monomer (Singleton) mode (singleton mode): Absolutely the most basic and useful pattern in JavaScript.

Singleton concept: Guaranteed only one instance of a class

The method of implementation: First determine whether the instance exists or not, there is a direct return, does not exist to create a return, which ensures that a class has only one instance object.

Use:
A. Used to partition the namespace and provide a unique access point from the global namespace to access the object.
B. Implement module internal protection, communication between modules
  
Pros: You can reduce the number of global variables in your Web pages (risk of using global variables in your Web pages), and you can avoid code conflicts (using reasonable namespaces) when developing multiple people.

Precautions for use:

Use of A.this
B. Closures are prone to memory leaks and do not need to be disposed of quickly.
C. Pay attention to the cost of new (inheritance)

Instance:

<script>//top Module (with the following banner module is a separate namespace, non-interference (self-protection), can communicate with each other)    vartop = {init: function () {            //Bind DOM elements first             This. render ();//Bind events for DOM elements again             This. bind (); }, A:4,//Quantity to be delivered        //render put all the DOM elements in the side.Render function () {            varme = This; Me.btn_a = $ (' #a '); },//bind Binding an event to an elementBind function(){            varme = This; Me.btn_a.click ( function(){                //business logic, defined belowMe.test ();        }); }, Test: function(){A =5; }    };//banner Module    varBanner = {init: function () {            //Bind DOM elements first             This. render ();//Bind events for DOM elements again             This. bind (); }, A:4,//Quantity to be delivered        //render put all the DOM elements in the side.Render function () {            varme = This; Me.btn_a = $ (' #a '); },//bind Binding an event to an elementBind function(){            varme = This; Me.btn_a.click ( function(){                //business logic, defined belowMe.test ();        }); }, Test: function(){            //a = 6;Top.a =6;//Directly call module top .... Achieving and Top communication}    };//initialization of each moduleTop.init (); Banner.init ();</script>

For more information, please refer to: http://www.cnblogs.com/TomXu/archive/2012/02/20/2352817.html

(2) Factory mode

Concept: defines an interface for creating objects that subclasses decide which class to instantiate . This pattern defers the instantiation of a class to a subclass. Subclasses can override interface methods to specify their own object types when they are created.

Use:

Suitable for:
A. Scenarios where objects are built more complex
B. You need to rely on a specific environment to create different instances.
C. Handle a large number of small objects with the same attributes.

Precautions:
A. Do not misuse the factory model, if only to produce a good few objects, the creation of the factory will only increase the complexity of the code. (will produce a large number of small objects in order to build a factory line)

Pros: eliminate coupling between objects (what is coupling?) is to interact with each other). By using the factory method instead of the new keyword and the concrete class, you can centralize all instantiated code in one place, helping to create modular code

<script>//Factory is a monomer (single case module)    varMyFactory = {};//Different factory linesMyfactory.product_shoes = function(){         This. Workers = -; Alert' Making Shoes ');    }; Myfactory.product_clothes = function(){         This. Workers = -; Alert' Making clothes '); };//Define a class whose instantiation is deferred to the following subclassMyfactory.manager = function(para){        return NewMyfactory[para] (); }//subclass, instantiate, decide which and what kind of things to produce    varsomebody = Myfactory.manager (' Product_shoes ');//alert (somebody.workers);</script>

Another very well-known example-the XHR factory:

varXmlhttpfactory = function(){};//This is a simple factory modelXmlhttpfactory.createxmlhttp = function(){      varXMLHttp =NULL;if(Window. XMLHttpRequest) {XMLHttp =NewXMLHttpRequest ()}elseif (window. ActiveXObject) {XMLHttp =NewActiveXObject ("Microsoft.XMLHTTP")    }returnXMLHttp; }//xmlhttpfactory.createxmlhttp () This method returns a Xhr object, depending on the circumstances of the current environment.     varAjaxhander = function(){      varXMLHttp = Xmlhttpfactory.createxmlhttp (); ...  }

Factory has a simple factory, the division of the abstract plant:

varXmlhttpfactory = function(){};//This is an abstract factory patternXmlhttpfactory.prototype = {//If you really want to call this method throws an error, it cannot be instantiated and can only be used to derive subclassesCreatefactory: function(){ThrownewError(' This was an abstract class '); }  }//derived sub-class, the beginning of the article has a basic introduction that has to explain the pattern of inheritance, do not understand can go to reference principle    varXhrhandler = function(){Xmlhttpfactory.call ( This);  }; Xhrhandler.prototype =NewXmlhttpfactory (); XHRHandler.prototype.constructor = Xhrhandler;//Redefine the Createfactory methodXHRHandler.prototype.createFactory = function(){       varXMLHttp =NULL;if(Window. XMLHttpRequest) {XMLHttp =NewXMLHttpRequest ()}elseif (window. ActiveXObject) {XMLHttp =NewActiveXObject ("Microsoft.XMLHTTP")   }returnXMLHttp; }

difference:
Simple factory: Used to produce any product in the same grade structure. ( inability to add new products )
Factory method: Used to produce fixed products in the same grade structure. (Support for adding any product)
Abstract Factory: Used to produce all products of different product families. (for adding new products, powerless; support for adding product families )

The above three plant methods have different levels of support in two directions: hierarchical structure and product family. So consider which method you should use depending on the situation.

Simple Factory Benefits: Clients can dispense with the responsibility to create product objects directly, but simply "consume" products. The simple factory model achieves the separation of responsibilities through this approach.
Factory method A bit: Allows the system to introduce new products without modifying the specific factory roles.
Abstract Factory Benefits: Provides an interface to clients to create product objects in multiple product families without having to specify product specific types

For more detailed differences in abstract factory simple factories, see: http://zyjustin9.iteye.com/blog/2094960

(3) Bridging mode

Concept: Separating the abstract part from its implementation, so that they can all change independently.

Purpose: Most commonly used in event monitoring. Bridging mode is useful when implementing APIs. In all modes, this model is easiest to implement immediately.

Advantage: It can be used to weaken the coupling between it and the classes and objects that use it, which is to isolate the abstraction from its implementation so that they change independently; this pattern has great benefits for the common time-driven programming in JavaScript. Bridging mode makes the API more robust, improves the modularity of components, facilitates simpler implementations, and increases abstraction flexibility.

//The wrong way    //This API is based on the function of the event listener callback function, which is passed as a parameter to the event object. This parameter is not used in this example, but only gets the ID from the This object. Addevent (element,' click ', Getbeerbyid); function(e){       varID = This. ID; Asyncrequest (' GET ',' beer.url?id= '+ ID, function(resp){          //callback ResponseConsole.log (' requested Beer: '+ Resp.responsetext);  }); }//Good way    //Logically analyze, pass the ID to the Getbeerbyid function, and the response result is always returned by a callback function. So, what we're doing now is programming for interfaces rather than implementations, isolating abstractions with bridge patterns.      function getbeerbyid(id,callback){Asyncrequest (' GET ',' beer.url?id= '+ ID, function(resp){Callback (Resp.responsetext)}); } addevent (Element,' click ', Getbeerbyidbridge); function getbeerbyidbridge(e){Getbeerbyid ( This. ID, function(beer){Console.log (' requested Beer: '+ beer);  }); }

(4) Decorator (Decorator) mode

Purpose: Adds a function (or method) to an object.

Concept: Dynamically add some additional responsibilities to an object . In terms of extension functionality , it is more flexible than generating subclasses.

The decorator pattern and the composition pattern have a lot in common, they all implement a uniform interface with the wrapped object and will pass any method bar to these objects. However, the combination mode is used to organize many sub-objects into a whole, while the decorator pattern is used to add methods to the existing objects without modifying them or deriving subclasses from them.

The decorator's process is transparent, which means that you can use it to wrap other objects, and then continue to do so using the object's previous method.

(5) combination (Composite) mode

Concept: Combine objects into a tree structure to represent a "partial-whole" hierarchy . It enables customers to have consistent use of individual objects and composite objects.

Combination mode is a model that is tailored to create a dynamic user interface on the web. With this pattern, you can use a single command to fire complex or recursive behavior on multiple objects. The combination mode excels at manipulating large numbers of objects.

Pros: 1. The programmer can use the same method to handle the collection of objects and the specific sub-objects thereof; 2. It can be used to organize a batch of sub-objects into a tree structure and make the whole tree accessible.

Scope of application: 1. There is a group of objects that are organized into a hierarchical system (concrete structures may not be known during development); 2. You want to be honest with this batch of objects or some of them.

In fact, the combination mode is a series of similar or similar objects together in a large object, by this large object to provide some common interface to manipulate these small objects, code reuse, easy to operate externally. For example, in the case of a form element, regardless of the page design, the general left input, for these input has the name and value properties, so you can use these input elements as members of the Form object, the Form object provides an external interface, You can implement some simple actions, such as setting the value of an input, adding/deleting an input, and so on.

(6) façade (facade) mode

Concept:
Façade mode is the core principle of almost all JavaScript libraries
A set of interfaces in a subsystem provides a consistent interface, and the façade pattern defines a high-level interface, which makes the subsystem easier to use, which is simply an organized pattern that can be used to modify the interfaces of classes and objects to make them easier to use.

Function: 1. Simplify the interface of the class; 2. Eliminate the coupling between the class and the customer code that uses it.

For example, the shortcut icons on the computer desktop are playing a role in the interface that directs the user to a place, and each operation is indirectly executed by some behind-the-scenes commands.

Four expansion and in-depth

There are many design patterns in detail, please refer to Uncle Tom's in-depth understanding of the JavaScript series blog, where a lot of design patterns are explained in detail:
Http://www.cnblogs.com/TomXu/category/338104.html

Front End Learning Summary (14) JavaScript design pattern

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.