JavaScript design mode and javascript Mode

Source: Internet
Author: User
Tags macbook

JavaScript design mode and javascript Mode
Preface

I recently read the book "JavaScript Design Patterns", which contains many knowledge points and cannot be digested for a moment. Remember it first.
Ps: For more information, see Uncle Tom's blog to understand the JavaScript series.

Constructor Mode

The Object constructor is used to create objects of a specific type-prepare objects for use and accept parameters that can be used by the constructor to set the value of member attributes and methods when creating objects for the first time.

function Car(model, year, miles) {    this.model = model;    this.year = year;    this.miles = miles;    this.toString = function() {        return this.model + " has done "+ this.miles + "miles";    };}

The above is a simple constructor mode version, but there is a performance problem: the toString () method is to re-define the new objects created for each Car, if multiple objects are created at the same time, resource waste is serious. Therefore, we generally use the following prototype constructor mode.
Ps: it is generally recommended that the constructor name start with an uppercase letter to distinguish between common functions.

Function Car (model, year, mille) {this. model = model; this. year = year; this. mile = mile;} // note that Object is used here. prototype. newMethod to avoid redefining the prototype object Car. prototype. toString = function () {return this. model + "has done" + this. miles + "miles" ;}; var landRover = new Car ("Land Rover", 2015,100 00 );

Currently, a single instance of toString can be shared among all Car objects.
The process of instantiating the new object of landRover is as follows:

Module Mode

In js, the Module mode is used to further simulate the concept of classes. In this way, a single object can have public/private methods and variables, thus shielding special parts from the global scope. (Using the concepts of self-executed functions and closures)

Var myNamespace = (function () {// Private counter variable var myPrivateVar = 0; // Private function var myPrivateMethod = function (foo) {console. log (foo) ;}; return {// public variable myPublicVar: "foo", mYPublicFunction: function (bar) {myPrivateVar ++; myPrivateMethod (bar );}};}) ();
Singleton Mode

"Singleton", as its name implies, limits the number of class instantiation times to only one. The simplest Singleton mode is the object literal method.

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

The difference between the static instance (object) and Singleton of the above class: when Singleton can be implemented as a static instance, it can also be delayed until the static instance needs to be used, it can save resources or memory.

// Method 1var mySingleton1 = (function () {// The instance maintains a Singleton application var instance; function init () {var privateVariable = "I'm private "; function privateMethod () {console. log ("I'm private");} return {publicProperty: "public", publicMethod: privateMethod};} return {getInstance: function () {if (! Instance) {instance = init ();} return instance ;};}) (); // method 2var mySingleton2 = function () {// cache instance var instance = this; // other content this. property = "value"; // rewrite the constructor mySingleton2 = function () {return instance ;};};
Observer (Observer) Mode

The observer mode is also called the publish/subscribe mode. An object (subject) maintains a series of objects (observer) dependent on it ), notify them of any changes to the status. The observer mode can be used to break down applications into smaller and more loosely coupled blocks to facilitate code management and potential reuse. Ps: the most direct application in this mode is DOM Event binding.

Var pubSub ={}; (function (q) {var topics ={}, subUid =-1; // publish or broadcast events, contains the specific topic name and parameters (such as transmitted data) q. publish = function (topic, args) {if (! Topics [topic]) {return false;} var subscribers = topics [toppic], len = subscribers? Subscribers. length: 0; while (len --) {subscribers [len]. func (topic, args) ;}return this ;}; // subscribe to an event using a specific name and callback function. When a topic or event is triggered, run the event q. subscribe = function (topic, func) {if (! Topics [topic]) {topics [topic] = [];} var token = (++ subUid ). toString; topics [topic]. push ({token: token, func: func}); return token;}; // Based on the tag reference on the subscription, the subscription is canceled through a specific topic. unsubscribe = function (token) {for (var m in topics) {if (topics [m]) {for (var I = 0, j = topics [m]. length; I <j; I ++) {if (topics [m] [I]. token = token) {topics [m]. splice (I, 1); return token ;}}} return false ;}}) (pubSub );

In addition, you can use the jQuery event binding on/off method to easily implement the Publish/Subscribe mode:

(function ($) {    var o = $({});    $.subscribe = function () {        o.on.apply(o, arguments);    };    $.unsubscribe = function () {        o.off.apply(o, arguments);    };    $.publish = function () {        o.trigger.apply(o, arguments);    };} (jQuery));
Mediator Mode

If the components of a system seem to have too many direct relationships, it may be necessary to have a central control point so that each component can communicate through this central control point. The intermediary mode promotes loose coupling by ensuring that the interaction between components is handled through this central point, rather than by applying each other through display. This mode can help us decouple the system and improve the reusability of components. A typical example in the real world is the airport traffic control system. The airport control tower acts as the intermediate point.
Another example is DOM Event bubbling and event delegation. If all the subscriptions in the system target the document instead of a single node, this document will effectively act as the intermediary. More advanced objects are responsible for notifying subscribers about interactive events, rather than binding events to a single node.

var mediator = (function() {    var topics = {},        subscribe = function(topic, fn) {            if (!topics[topic]) {                topics[topic] = [];            }            topics[topic].push({                context: this,                callback: fn            });            return this;        },        publish = function(topic) {            var args;            if (!topics[topic]) {                return false;            }            args = [].prototype.slice.call(arguments, 1);            for (var i = 0, l = topics[topic].length; i < l; i++) {                var subscription = 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;            }        };})();

Intermediary and observer
In observer mode, a single object with encapsulation constraints does not exist. Observer and Subject are used together to maintain constraints. Communication is performed by multiple observers and multiple specific classes. Each specific class usually contains multiple observers, sometimes an observer in a specific class is also a specific class of another observer. The intermediary mode restricts objects to communicate through Mediator strictly.

Prototype Mode

The prototype mode is a mode for creating objects by cloning based on existing Object Templates. The common mode is as follows: it does not contain any initialization concepts. It only links objects to the prototype.

var beget = (function() {    function F() {};    return function(proto) {        F.prototype = proto;        return new F();    };})();

In addition, the ECMA5 standard defines a method,Object. create (proto, [propertiesObject])Create an object with a specified prototype and several specified attributes. This method can easily implement Object Inheritance without using an empty function for transition.

Factory Model

If the factory mode is not displayed, a constructor is required to create an object by providing a common interface. We can specify the type of the factory object to be created. This mode delays the instantiation of a class to the subclass. Subclass can override the interface method to specify its own object type during creation.

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 in different environments
  • When processing many small objects or components that share the same attributes
Decorator Mode

The decoration mode provides the ability to dynamically add behaviors to the existing classes of the system. Instead of relying heavily on the object creation method, it focuses on extending its additional functions. The basic idea is to add (decoration) attributes or methods to basic objects, rather than subclass them.
The modifier is used to add new features in the form of a reload method. In this mode, you can add your own actions before or after the decorator to achieve a specific purpose, used to add new actions to different objects.

// Decorated object constructor function MacBook () {this. cost = function () {return 997;}; this. screenSize = function () {return 11.6};} // Decorator 1 function Memory (macbook) {var v = macbook. cost (); macbook. cost = function () {return v + 75 ;}/// Decorator 2 function Engraving (macbook) {var v = macbook. cost (); macbook. cost = function () {return v + 200 ;}/// Decorator 3 function Insurance (macbook) {var v = macbook. cost (); macbook. cost = function () {return v + 250 ;};}
Flyweight Mode

The metadata mode is designed to share as much data as possible with related objects to reduce memory usage (such as application configuration and status) in applications ).
There are two ways to apply the enjoy mode. The first type is used for the data layer to process shared data of a large number of similar objects stored in the memory. The second method is used for the DOM layer. Flyweight can be used as the central event manager to avoid adding event handlers to each child element in the parent container, instead, the event handler is appended to the parent container.
For details, refer to Uncle Tom's blog-a deep understanding of the JavaScript System (37): the metadata mode of design patterns

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.