In-depth understanding of JavaScript design Patterns

Source: Internet
Author: User

Design Patterns

Design patterns are naming, abstracting, and identifying common design structures that are useful for reusable object-oriented design.

Design patterns determine the classes and their entities, their roles and collaborations, and their assigned responsibilities.

Each design pattern focuses on an object-oriented design challenge or problem.

It describes whether it can be used under the constraints of other designs. Use it after the consequences and gains and losses.

Since we must finally implement our design pattern, each design pattern provides examples of code to illustrate the implementation.

Although design patterns are described as object-oriented design, they are based on solutions that have been implemented by mainstream object-oriented languages ... ".

Kinds

The design pattern can be divided into several different types.

In this part we will be divided into three categories: creation design pattern, structure design pattern, behavior design pattern.

Create Design Patterns

The creation design pattern focuses on the mechanism method of object creation, through which objects are created in a way that adapts to the working environment. The primary object creation method may add additional complexity to the project, and the purpose of these patterns is to solve the problem by controlling the creation process.

Some of the patterns that fall into this category are: Constructor mode (Constructor), Factory mode (Factory), abstract Factory mode (abstraction), prototype mode (PROTOTYPE), Singleton mode (Singleton), and builder mode (builder).

Structural Design Patterns

structural patterns focus on the composition of objects and the way in which they are commonly recognized to implement relationships between different objects. This pattern helps to change a part of the system, and the entire system structure does not need to change. The same pattern helps to reorganize parts of the system that do not achieve a certain purpose.

The modes under this category are: Decoration mode, appearance mode, and the mode of sharing. Adapter mode and proxy mode.

Behavioral Design Patterns

Behavioral Patterns focus on improving or streamlining communication between different objects in the system.

Behavior patterns include: iteration patterns. Mediator mode, observer pattern, and interview mode.

The following is a way to deepen our understanding of design patterns by separating each of the design patterns that are often used.

Constructor mode

A constructor is a special function that initializes an object when the memory of the new object is allocated. The object constructor is the object that is used to create a special type of object, first it is intended to be used. Second, when the object is first created, it receives the number of references. The constructor is used to assign values to the members ' properties and methods.

Because JavaScript does not support the concept of classes, you must use Newkeyword to initialize objects through the constructor.

A basic constructor code such as the following:

function Car (model, year, miles) {   This.model = model;  This.year = year;  This.miles = miles;   this.tostring = function () {    return This.model + "have done" + This.miles + "Miles";  };} Use://We can demonstrate a sample of a carvar civic = new Car ("Honda Civic", "20000"), var mondeo = new Car ("Ford Mondeo", 2010, 5000 ); Open the browser console to view the output values of the ToString () method for these objects//outputs of the ToString () methods being called on//these objectsconsole.log (civic.tost Ring ()); Console.log (mondeo.tostring ());

But this kind of words, the inheritance is more troublesome, and each car constructor created by the object, ToString and other functions will be defined again. So we're going to use prototypes to implement the best constructors:

function Car (model, year, miles) {   This.model = model;  This.year = year;  This.miles = miles; }  //Note Here we use note here, we are using Object.prototype.newMethod instead of//Object.prototype. To prevent us from defining the prototype object again Car.prototype.toString = function () {  return This.model + "have done" + This.miles + "Miles";}; Use: var civic = new Car ("Honda Civic", "20000"), var mondeo = new Car ("Ford Mondeo", 2010, 5000); Console.log (Civic.tostring ()); Console.log (mondeo.tostring ());

Factory mode

A factory can provide a common interface for creating objects. We are able to specify the type of factory object that we want to be created in. That's a simple point. Like a water dispenser, coffee or milk depends on which button you press.

The simple factory model can be embodied in the creation of Ajax objects, can be understood by the $.ajax method in jquery, and can be understood through an Ajax method that I write myself. Address in: Http://runjs.cn/code/j5dkikwu


Ajax ("Test002.txt", {type: "GET", Data:{name: "Liuf", Age:23},onsuccess:function (RESPONSETEXT,XHR) { document.getElementById ("Input"). Value=responsetext;},onfail:function () {//document.write ("fail");});

Ajax is actually a factory method, and whether it is using the Get method or the Post method is determined by the following code. That's what we said earlier. "A factory can provide a common interface for creating objects, and we can specify the type of factory objects we want to create in this."

Single-Case mode

The single-instance pattern is so called. is because it restricts a class to have only one instantiated object . The classic way to achieve this is. Create a class that includes a method that creates a new instance object without the presence of an object.

Assuming an object exists, this method simply returns a reference to the object. But JavaScript is inherently non-class, so simply put. Just do not create, there is no direct use.

So let's look at the real case. A mask layer appears after clicking on a button, which is a frequently used requirement. The code is as follows:

var createmask = function () {    return Document,body.appendchild (  document.createelement (div)  );} $ (' button '). Click (function () {    var mask  = Createmask ();    Mask.show (); })

The problem with this writing is that each call to Createmask creates a new div, although it can remove the mask layer when it is hidden, which can still lead to performance loss. Then be able to do for example the following improvements. is to create a div at the beginning of the page. The code is as follows:

var mask = document.body.appendChild (document.createelement (' div ')); $ (' button '). Click (function () {    mask.show ();})

This really ensures that the page will only create a mask layer, but there is also a problem, that is, if the user does not need to use this div, it is not in vain to create it. So we can use a variable to infer whether a DIV has been created, such as the following:

var mask; var createmask = function () {if (mask) return mask; else{mask = Document,body.appendchild (  document.createelement (d IV)  ); return mask; } }

This looks good, but mask acts as a global variable. Does it cause pollution? So the best way for example is the following:

var createmask = function () {  var mask;  return function () {       Return mask | | (Mask = document.body.appendChild (document.createelement (' div.))  }} ()

This is what we said earlier, "No creation, no direct use." Yes, the singleton pattern is so simple that design patterns are actually not difficult. We have actually been practical in programming, only to find ourselves.

Bridging mode

Bridging mode is the separation of the implementation part and the abstract part. So that the two can change independently. When implementing the API, the bridging mode is used very often.

Let's take JavaScript's foreach method as an example:


ForEach = function (ary, FN) {for  (var i = 0, L = ary.length; i < L; i++) {    var c = ary[i];    if (Fn.call (c, I, c) = = = False) {      return false;}}   }

You can see that the foreach function does not care about the detailed implementation in FN . The logic inside the FN is not affected by the rewrite of the foreach function.

Use code such as the following:

foreach ([n/A], function (i, n) {  alert (n*2)}) foreach ([n/A], function (i, n) {   alert (n*3)})


Appearance mode

The appearance pattern is a ubiquitous pattern, and the façade mode provides a high-level interface, which makes the client or subsystem calls more methods.

Example:

var getName = function () {  return ' Svenzeng '}var getsex = function () {   return ' man '}

Now I'm going to call two methods, and I'll be able to invoke it using a higher-level interface:

var getuserinfo = function () {  var info = getName () + getsex ();  return info;}

This makes it easy to assemble, assuming that two is written into a function at the beginning, it is not possible to invoke only one of them alone.


Enjoy meta mode

The enjoy meta-mode is a classic structured solution for optimizing repetitive, slow, and inefficient data sharing code. Its goal is to reduce the use of memory in the application (e.g., application configuration, State, etc.) by sharing as much data as possible with the relevant object. In layman's words, the use of meta-mode is used to reduce the number of objects required by the program.

For example, a waterfall stream in a webpage. Or in a WEBQQ friend list. Every time you pull down. will create a new div. So suppose there are very pairs of div? Isn't the browser a dead card? So we'll think of a way. is to remove the div that has disappeared out of sight. This allows the page to maintain a certain number of nodes, but frequent deletion and addition of nodes can lead to significant performance overhead.

This is the time to use the enjoy meta mode, which can provide some shared objects for reuse. For example, only 10 div can be displayed on the page, which is always the 10 div in the user's line of sight that can be written as a privilege.

The principle is actually very easy, put the newly hidden div into an array, when the need for Div, first from the array, assuming that the array is not already, and then create one again. The div in this array is the sharing element, each of which can be used as a carrier for whatever user information. Code such as the following:

var Getdiv = (function () {    var created = [];    var create = function () {          return Document.body.appendChild (document.createelement (' div '));    }    var get = function () {         if (created.length) {              return created.shift ();          } else{                return Create ();           }     } /* If an event is used to listen to a div that just disappears out of sight, it can actually be implemented by listening to the scroll bar position *      /userinfocontainer.disappear (function (div) {              Created.push (div);        }) }) ()  var div = getdiv ();  div.innerhtml = "${userinfo}";

Adapter mode

The adapter pattern is to convert the interface of one class into another interface that the customer wants. Popular point of saying. Will be like an Apple phone can not be poor in the computer chassis, must have a converter. And this converter is the adapter.

In the program adapter mode is also used frequently to adapt to 2 interfaces, for example, you are now using a self-defined JS library. There is a method $id () that gets the node based on the ID. One day you think the $ in jquery is more cool, but you don't want your project teacher to learn new libraries and grammars. That one adapter will get you over this thing.

$id = function (ID) {   return jQuery (' # ' + ID) [0];}

So you don't have to change one more.

Proxy mode

The proxy mode is to take an access to an object and give it a proxy object to manipulate.

In a more popular sense, program apes write daily newspapers every day. The daily paper will be given to the director. But assume that all people are sent directly to the director. The director won't be able to work.

So each person will send their daily newspaper to their leader, and then forwarded by the leader to the director. The leader is the agent.

There are also many scenarios in which the proxy mode is used, for example, when a large number of DOM operations are done, we create the document fragment and then unify it into the DOM tree.

The scale is as follows:


Broker mode

The mediator pattern is the shared-by-observer object in the Observer pattern.

The direct advertisement/subscription relationship between the objects in the system was sacrificed. Instead, maintain the central node of a communication. There is a difference between the broker pattern and the proxy pattern. Differences such as the following:

The Mediator object allows the objects to be referenced without reference to each other. This makes it loosely coupled and can independently change the interaction between the transparency.

In layman's words, banks can also be seen as intermediaries between depositors and lenders. Depositor a doesn't care who borrowed his money at last.

Lender B also does not care about whose deposits the money he borrowed comes from. Because of the presence of intermediaries. The deal was made so convenient.

In programming, is the controller in the famous MVC structure a mediator? Take backbone for example. The data in a mode is not sure which view is used last. The data needed for view can also come from a random mode. All binding relationships are determined in controler. The mediator turns the complex many-to-many relationship into 2 relatively simple 1-to-many relationships.

The demo sample code is as follows:

var mode1 = Mode.create (),  mode2 = Mode.create (), var view1 = View.create (),   view2 = View.create (), var controler1 = Controler.create (mode1, View1, function () {  view1.el.find (' div '). bind (' click ', Function () {    this.innerhtml = mode1.find (' data ');  } )}) var controler2 = controler.create (Mode2 view2, function () {  view1.el.find (' div '). bind (' click ', function () { c6/>this.innerhtml = mode2.find (' data ');  } )})
Observer pattern

The observer pattern is such a design pattern.

An object, called the Observer, maintains a set of objects called observers that depend on the observer, who voluntarily notifies them of their state regardless of change.

When an observer needs to notify the observer of some change, it will be broadcast, and the broadcast may include some data specific to this notification.

When a particular observer is no longer required to receive notification from the observer who is in it, the observer is able to remove it from the group being maintained.

The popular point of view is that the interviewer is the interviewee. And the person waiting to be notified is the observer.

DOM events that are normally touched in JavaScript. is actually a manifestation of an observer pattern:


Div.onclick  =  function Click () {    alert (' click ')}

Just subscribe to the div's Click event, and when you click on the div, the click function will run.

Observer mode can be very good for decoupling between modules, if a multi-person project, I am responsible for the map and gamer mode:


LoadImage (  imgary,  function () {map.init (); Gamer.init (); } )
<p> and others are responsible for the maintenance of loadimage methods. Let's say one day I'm going to add a sound module, and I have no right to use someone else's code. Just waiting for someone else to come back to join: </p><pre name= "code" class= "HTML" >loadimage (  imgary,  function () {map.init (); Gamer.init (); Sount.init (); } )

So we can do the following modifications, for example:

Loadimage.listen (' Ready ', function () {     map.init ()}) Loadimage.listen ("Ready", function () {    gamer.init ();}) Loadimage.listen (' Ready ', function () {    sount.init ();})

After the LoadImage is finished. Instead of worrying about what the future will send, it just needs to send a signal:


Loadimage.trigger (' ready ');


All objects listening to the ready event will be notified. This is the application scenario for the Observer pattern.


Here it is. The often-used design patterns are finished, and a deeper understanding of the JavaScript series will be over.







In-depth understanding of JavaScript design Patterns

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.