Nine design Patterns in the <<javascript mode >>

Source: Internet
Author: User
Tags compact set time hasownproperty

Mode one: Monomer mode

Function: To ensure that there is only one instance of a particular class, commonly used as a common and shared (multiple methods can be used as reference objects) to solve a particular problem

JavaScript implements the monomer problem: each time an instance object is new, the instance objects are not equal, the two are different objects, non-singleton objects

Realize:

① static Property instances

Caching a single instance in the static properties of the Universe constructor (this current object)

Code implementation:

function Universe () {   if (typeof universe.instance = = = = "Object") {       return universe.instance;   }   This.start_num = 0;   This.nam = "Su";     Universe.instance = this;   return this//implicit return}  var u1 = new Universe () var u2 = new Universe (); u1=== U2  //True

Cons: Externally modifiable instance properties

② closure instances (closures to protect individual instances, private variables)

overriding constructors, accessing private variables through closures

Code implementation:

function Universe () {   var instance = this;   This.start_num = 0;   This.nam = "Su";     Universe=function () {    return instance;  }}  var u1 = new Universe (); var U2 = new Universe (); u1=== U2  //True

Insufficient: Uni.constructor's constructor differs from Universe ()

FIX: Reset constructor pointer

Mode two: Factory mode

Role: To provide customers with an interface to create objects, depending on the input type (parameters) to create different objects, created objects are child objects, all inherit the parent object thought

Realize:

① Custom implementations:

  function carmaker () {} CarMaker.prototype.driver = function () {Console.log ("I have" + this.doors + "gate");    Return "I have" + this.doors + "a door";        }//static constructor carmaker.factory = function (type) {var constr = type;        var Newcar;               If the constructor does not exist, an error occurs if (typeof carmaker[constr]! = "function") {throw{name: "Error",           Message:constr + "doesn ' t exit!!" }}//prototype inherits the parent class, inheriting only once if (typeof carmaker[constr].prototype.driver!== "function") {Carmaker[c  Onstr].prototype = new carmaker ();        Focus: inherited}//Create a new instance Newcar = new Carmaker[constr] ();  return newcar;    Returns a new instance of} CARMAKER.SUV = function () {this.doors = 4;    } carmaker.compact = function () {this.doors = 10;    } carmaker.convertible = function () {this.doors = 8;    }//using var SUV = carmaker.factory (' SUV ');    var compact = carmaker.factory (' compact '); var convertible = carmaker.factory (' convertible ');    Suv.driver ();    Compact.driver (); Convertible.driver ();

Inherit instance new child object return new child object

② system built-in objects factory new object ()

var o = new Object (); var n = new Object (1); var s = new Object (' 1 '); var B = new Object (true); O.constructor = = = Object/True;n.constructor = = = numer//True;s.constructor = = = string//True;b . constructor = = = boolean//true;

Mode three: Iterative mode

Function: An API that provides manipulating data structures for related objects, such as the operation of a list structure

Realize:

var egg = (function () {       var index = 0;       var data = [1,2,3,4,5];       var length = data.length;       return {           next:function () {              var element;              if (!this.hasnext) {                return null;              }              element = Data[index];              index = index + 2;              return element;           },           hasnext:function () {               return index < length;}}       ;   } ());    Use, iterate iterate over the data structure    while (Agg.hasnext ()) {        console.log (agg.next);    }

Pattern Four: Decorator mode

Function: To extend the function of an object through inheritance and overloading

Realize:

function Sale (price) {this.price = Price | | 100;     } Sale.prototype.getPrice = function () {return this.price;     } sale.decorators = {}; Sale.decorators.fedtax = { //will inherit as newobj implementation and Overload GetPrice Getprice:function () {var price = This.ub  Er.getprice ();            This.uber is: Newobj.uber = F.prototype;            Price + = Price * 5/100;         return price;            }} Sale.decorators.quebec = {getprice:function () {var price = This.uber.getPrice ();            Price + = Price * 7.5/100;        return price;         }} Sale.decorators.money = {getprice:function () {return "$" + this.uber.getPrice (). toFixed (2); }} SALE.DECORATORS.CDN = {getprice:function () {return "cnd$" + this.uber.getPrice (). To        Fixed (2);      }} Sale.prototype.decorate = function (decorator) {var F = function () {}; var overrides = This.constructor.decorators[decorAtor];       var i,newobj;       F.prototype = this;       NEWOBJ = new F ();       Newobj.uber = F.prototype;          For (I-in overrides) {if (Overrides.hasownproperty (i)) {//All non-prototype properties are inherited to newObj newobj[i] = overrides[i]   }} return NEWOBJ;    }//usage var sale = new Sale (100);    Sale = sale.decorate (' Fedtax '); Console.log (Sale.getprice ());

Mode five: Policy mode

function: Supports selecting an algorithm at run time, the client of the code can use the same interface to work (the Validate interface in the instance), but it does choose an algorithm from multiple algorithms to handle a particular task based on the context in which the customer is trying to execute the task ( Executes the context validate in the types according to the settings in config). Provides a variety of policy methods for an object for free choice.

Scenario: Forms validation is commonly used

Realize:

   Policy mode//now have a set of data to do check var validator = {types: {},//All available check functions Validator.types[xxx] Config: {            },//Check format messages: [],///error message Validate:function (data) {//interface method, data is the DataSource object var type;            var msg;            var checker;            var Result_ok;            Reset All messages this.messages = [];  For (key in data) {if (Data.hasownproperty (key)) {//Traverse all private properties type = This.config[key]; All inspection methods under config checker = This.types[type]; Validator.types.                    [Type] if (!type) {//config is undefined, skip the continue directly;                            }//End Type if (!checker) {throw {name: ' E ',                    Messages: "Es" +type}}//End!checker                    RESULT_OK = Checker.validate (Data[key]); if (!resuLT_OK) {//if authentication fails MSG = key + "Data type is invalid, the value must be" + checker.intructions;                    This.messages.push (msg);        }}} return This.haserrors ();        }, Haserrors:function () {return this.messages.length!== 0;   }    };  var studentdata = {age: ' SD ',//error demonstration Desc:12};   Set the check format corresponding function for this set of data Validator.config = {age: ' Isnumber ', desc: ' Isstring '};       Define Check function Validator.types.isNumber = {validate:function (data) {return!isnan (data);   }, Intructions: "Data must be a numeric type"}; validator.types.isString = {validate:function (data) {return (typeof data = = = "string")}, I    Ntructions: "Data must be a character type"};    Put the data into the ' Check total function ' in validator.validate (Studentdata);    If an error occurs, then the output error if (Validator.haserrors ()) {console.log ("\ n") {Validator.messages.join (")"); }
Error demonstration Output://The Age data type is invalid, the value must be the data must be a numeric type//DESC data type is invalid, the value must be the data must be a character type

Pattern Six: Appearance mode

Role: Provides an alternative interface for objects to wrap older objects to make them more compatible

Scenario: Compatible API differences between browsers, such as IE (return false) and Ff,chrome (Preventdefault), which are not the same as the default behavior API, are packaged into a unified stop () API through the appearance mode to hide the differences behind the skins. It also applies to re-engineering and refactoring objects, creating a look on the original object and replacing it with the old code.

Realize:

var myevent = {     Stop:function (e) {        e.preventdefault ();        E.stoppropagation ();   }   //};

  

Mode Seven: Proxy mode

Function: An object acts as an interface to another object, between the object's client and the object ontology (client, server), which protects the object's access, attempts to make the object ontology do less work, and maximizes performance savings.

Scenario: In a Web application, the merging of HTTP requests and the caching of network data, example click on the title to expand the video content (video content is obtained by the server).

Realize:

    Defines a proxy agent object//proxy object takes over the communication between HTTP and videos/proxy object with a 50ms delay to merge all requests during that time//proxy establish an empty queue to collect 50ms received video I   D, then empties the queue, and also calls//-> HTTP and provides it with a callback function. var proxy = {IDs: [], delay:50, Timeout:null, Callback:null, Context:null, M          Akerequest:function (Id,callback,context) {//Join to queue This.ids.push (ID);          This.callback = callback;        This.context = context;            Set time-out if (!this.timeout) {this.timeout = SetTimeout (function () {Proxy.flush ();         },this.delay);           }}, Flush:function () {http.makerequests (This.ids, "Proxy.handler");           Purge timeout settings and queue this.timeout = null;       This.ids = [];           }, Handler:function (data) {var I,max; Single Video if (parseint (data.query.count,10) = = = 1) {Proxy.callback.call (proxy.context,data.query.resu Lts. Video);//Call and bind context to Proxy.conteXT return; }//Multiple videos for (var i= 0,max = Data.query.results.video.length;i < max;i++) {proxy.ca           Llback.call (Proxy.context,data.query.results.video[i]); }       }   };

Pattern Eight: Broker mode

Function: In order to decouple the objects and objects in the application, the program maintainability is higher. Applications are made up of large and small objects, the need for communication between objects, once the size of the program expands, objects increase, the higher the coupling between objects, the higher the coupling between objects, the program maintainability will become worse (modify an object will affect many objects).

Application Scenario: multiple (multi-) human (object) Interaction scenarios, such as games ...

Implementation: (Traditional implementation: Interaction between two objects, pattern implementation: Adding an intermediary between objects (mediator) to provide communication for two objects)

  Example: Double click score Game//Participant object: Player (player 1+ player 2), scoreboard, Broker//player notification broker, mediator handles returning it to player function player (name) {//Player object        THIS.name = name;    This.point = 0;          } Player.prototype.play = function () {This.point +=1; Mediator.played (); Notification Mediator} var scoreboad = {//Scoreboard object Element:document.getElementById (' Scorebox '), update:funct            Ion (Score) {var i;            var msg = ';  For (i in score) {if (Score.hasownproperty (i)) {msg = i + ":" + score[i] + "/n";        Show Score Object home: +}} This.element.innerHTML = msg;    }    }; Next is the Broker object var mediator = {players: {},//places all players in this global object Setup:function () {var players           = This.players;           Players.home = new Player (' master ');        Players.guest = new Player (' guest ');           }, Played:function () {var players = This.players;         var score = {      Home:players.home.points, Guest:players.guest.points}; Scoreboad.update (score);//Returns the score to the scoreboard, the scoreboard is responsible for displaying}, Keypress:function (e) {if (E.which = = = 49) {//Player 1 button               1 Mediator.players.home.play ();           Return                } if (E.which = = = 48) {//Player 2 Button 0 mediator.players.guest.play ();            Return    }        }    };    Run Mediator.setup ();    window.onkeypress = mediator.keypress;       Game ends in 30 seconds setTimeout (function () {window.onkeypress = null;    Alert (' Game Over '); },30000);

Note: The proxy mode is similar to the broker mode, so what is the difference between them?

A: The agent is within the scope of the object's permission to operate, that is, only for an object, and the intermediary, is solely responsible for processing, can target multiple objects

Pattern NINE: Observer pattern

Role: Widely used in client programming, such as the operation of an event is an example of a pattern. In an application, not one object invokes another object, but one object subscribes to a specific activity of another object and gets a notification (callback) after the state changes. For example, a Window object subscribes to a click Click event

Application Scenario: Asynchronous Programming

Realize:

1, magazine subscription

2. Key game

Nine design Patterns in the <<javascript mode >>

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.