JavaScript Design Patterns

Source: Internet
Author: User
Tags uppercase letter macbook

Objective

Recently read the book "JavaScript design Mode". There is a lot of knowledge in the book, which can not be digested in a moment. Write it down first.


PS: Another part of the content of Uncle Tom Blog in-depth understanding of the JavaScript series

Constructor (Constructor) mode

The object constructor is used to create objects of a specific type-prepare objects for use, and at the same time accept the parameters that the constructor can use to set the values of member properties and methods when the object is first created.

f Unction  car   (model, year, miles)  {    Span class= "Hljs-keyword" >this . Model = model;    this . Year = year;    this . Miles = Miles; this . toString =  function   ()  { return  this . Model + " have done " + this    . Miles +  "Miles" ; };}

Above this is a simple constructor pattern version number. But there is a performance problem: ToString () is defined again for each new object created by car. Suppose you create multiple objects at the same time. The waste of resources is more serious. So we generally use the following constructor pattern with the prototype (prototype).
PS: It is generally recommended that the constructor name begin with an uppercase letter in order to distinguish between normal functions.

 function Car(model, year, Mille) {     This. model = model; This. year = year; This. Mile = Mile;}//Note use Object.prototype.newMethod here to avoid defining prototype objects againCar.prototype.toString = function() {    return  This. Model +" have done"+ This. Miles +"Miles";};varLandrover =NewCar ("Land Rover", -,10000);

Today, a single instance of ToString can be shared between all car objects.


The process of instantiating this new object Landrover:

    1. Create a new object and have the this pointer point to the new object
    2. Assigns the prototype object member of the constructor to the prototype chain of the newly created object
    3. Run the code in the constructor body to initialize the new object
    4. Returns the new object created
Module mode

In JS, the module pattern is used to further simulate the concept of a class. Through such a way. Enables a single object to have public/private methods and variables that mask a particular part from the global scope.

(using self-running functions and closure concepts)

var  MyNamespace = ( function   ()  { //private counter variable  var  myprivatevar = 0 ; //Private Function  var  myprivatemethod =  function   { console.log (foo); }; return  {//public variable  mypublicvar:  "foo" , mypub Licfunction: function   ( Bar)  { Myprivatevar + +; Myprivatemethod (bar); } };}) ();
Singleton (Singleton) mode

The "singleton" as the name implies is that it restricts the number of instances of a class to be instantiated only once. And the simplest singleton pattern is the object literal method.

var mySingleton = {    "myBlog",    function() {}};

There is a difference between static instances (objects) and singleton of the above class: When Singleton can be implemented as a static instance, it can delay the build until a static instance is required to conserve resources or memory.

//Mode 1varMySingleton1 = ( function() {    //instance maintains an application of singleton    varInstance function init() {        varPrivatevariable ="I ' m private"; function privatemethod() {Console.log ("I ' m private"); }return{publicproperty:"Public", Publicmethod:privatemethod}; }return{getinstance: function() {            if(!instance)            {instance = init (); }returnInstance }    };}) ();//Mode 2varMySingleton2 = function() {    //Cache instance    varInstance = This;//other content     This. property ="Value";//overriding constructorsMySingleton2 = function() {        returnInstance };};
Viewer (Observer) mode

The Observer pattern is also known as the Publish/subscribe (Publish/subscribe) pattern. Where an object (subject) maintains a series of objects that depend on it (the observer), proactively notifies them of any change in state.

Using the Observer pattern allows the application to be decomposed into smaller, more loosely coupled blocks for code management and potential reuse. PS: The most direct application of this mode is DOM event binding.

varPubSub = {};( function(q) {    varTopics = {}, Subuid =-1;//Announcement or broadcast event. Include specific topic names and parameters (for example, data passed)Q.publish = function(topic, args) {        if(!topics[topic]) {return false; }varSubscribers = Topics[toppic], len = subscribers? Subscribers.length:0; while(len--)        {subscribers[len].func (topic, args); }return  This; };//Subscribe to events by a specific name and callback function, Topic/event run event when triggeredQ.subscribe = function(topic, func) {        if(!topics[topic])        {Topics[topic] = []; }vartoken = (++subuid). toString; Topics[topic].push ({token:token, func:func});returnToken };//Based on the tag reference on the subscription. Unsubscribe via specific topicQ.unsubscribe = function(token) {         for(varMinchTopics) {if(Topics[m]) { for(vari =0, j = topics[m].length; I < J; i++) {if(Topics[m][i].token = = token) {Topics[m].splice (I,1);returnToken }                }            }        }return false; };}) (PubSub);

In addition, it is easy to implement the Publish/subscribe mode by using jquery events to bind the On/off method:

(function ($) {    var o = $({});    function () {        arguments);    };    function () {        arguments);    };    function () {        arguments);    };} (jQuery));
Mediator (mediator) mode

Assuming that there are too many direct relationships between the components of a system, it may be time to have a central control point so that the individual components can communicate through the central control point. The way in which the mediator pattern facilitates loose coupling is to ensure that the interaction of the components is handled through this central point, rather than applying each other through the display. Such a pattern can help us decouple the system and improve the reusability of the components. A typical example of the real world is the airport's traffic control system, which is the central point of the airport control tower.


Another example is DOM event bubbling and event entrusting.

Assuming that all subscriptions in the system are for document documents rather than individual node nodes, the document effectively charges its mediator. Higher-level objects assume responsibility for notifying subscribers about interactive events, rather than events that are bound to a single node.

varMediator = ( function() {    varTopics = {}, subscribe = function(topic, fn) {            if(!topics[topic])            {Topics[topic] = []; } topics[topic].push ({context: This, CALLBACK:FN});return  This; }, publish = function(topic) {            varArgsif(!topics[topic]) {return false; } args = [].prototype.slice.call (arguments,1); for(vari =0, L = topics[topic].length; I < L; i++) {varsubscription = Topics[topic][i];            Subscription.callback.apply (Subscription.context, args); }return  This; };return{publish:publish, subscribe:subscribe, Installto: function(obj) {Obj.subscribe = subscribe;            Obj.publish = publish; }        };}) ();

intermediaries and observers
In the Observer pattern. There are no single objects that encapsulate constraints. The Observer observer and the detailed class subject are coordinated to maintain the constraints, and communication is interacted with by multiple observers and multiple detailed classes: Each detail class usually consists of several observers, and sometimes one observer in the detail class is also a detailed class of observers.

The intermediary mode achieves this by restricting the object to communicate strictly through mediator.

Prototype (Prototype) mode

Prototype mode is a template based on an existing object. The mode of creating objects by cloning. Common patterns such as the following: Do not include the concept of any initialization, only the object is linked to the prototype.

var beget = (function() {    function F() {};    returnfunction(proto) {        F.prototype = proto;        returnnew F();    };})();

In addition, a method is defined in the ECMA5 standard. object.create (Proto, [Propertiesobject]) creates an object that has a specified prototype and several specified properties. This method can easily implement object inheritance without having to transition through an empty function.

Factory mode

Factory mode does not show the need to use a constructor, by providing a common interface to create objects, we can specify the type of factory object that you want to create. 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.

var  Car = ( function   ()  { var  Car = function   (options)  { this . Doors = Options.doors | | 4 ; this . State = Options.state | |  "brand new" ; this . Color = Options.color | |  "silver" ; }; return  function   (options)  { return  new  Car (options); };}) ();

When to use:

    • When object or component settings involve high complexity
    • When you need to easily generate different instances of objects based on the different environments in which they are located
    • When dealing with very many small objects or components that share the same properties
Decorative (Decorator) mode

Decorative patterns provide the ability to dynamically add behaviors to existing classes of the system, and do not rely heavily on how objects are created. Instead, focus on extending its extra functionality.

The basic idea is to add (decorate) properties or methods to the base object. Instead of sub-class.
Decorators are used to add new functionality in the form of overloaded methods. The pattern can be preceded or followed by the decorator to add its own behavior to achieve a specific purpose, for different objects to join the new behavior.

//Decorated object constructors function MacBook() {     This. Cost = function() {return 997;}; This. screensize = function() {return 11.6};}//Decorator 1 function Memory(macbook) {    varv = macbook.cost (); Macbook.cost = function() {returnV + the;};}//Decorator 2 function engraving(macbook) {    varv = macbook.cost (); Macbook.cost = function() {returnV + $;};}//Decorator 3 function Insurance(macbook) {    varv = macbook.cost (); Macbook.cost = function() {returnV + -;};}
Enjoy meta (Flyweight) mode

The enjoy meta-mode is designed to reduce the use of memory in your application by sharing as much data as possible with related objects (for example, application configuration.) Status, etc.).
There are two ways to use the enjoy meta mode. The first is for the data layer, which handles the shared data of a large number of similar objects stored in memory. The other is for the DOM layer. Flyweight can be used as a central event manager to avoid adding event handlers to each child element in the parent container, but instead attaching an event handler to the parent container.
Detailed reference to Uncle Tom's blog post-in-depth understanding of the JavaScript system (37): Design mode to enjoy the meta-mode

JavaScript Design Patterns

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.