Common JavaScript design patterns (1)

Source: Internet
Author: User

Peter Seibel, author of Practical Common Lisp, once said that if you need a pattern, there must be something wrong. The problem he mentioned is that due to the inherent defects of the language, he had to seek and summarize a general solution.

Whether it is weak or strong, static or dynamic language, imperative or declarative language, each language has inherent advantages and disadvantages. A Jamaica athlete has some advantages in sprint and boxing, and lacks some in yoga practice.

The magician and Shadow Priest can easily become an excellent helper, and an enemy method carrying a map of Macon may be slightly embarrassed. In the program, it may take a lot of effort to implement the modifier in the static language, and js can throw the method to the object at any time, so that the modifier mode becomes a chicken in js.

There are still few books about the Javascript Design pattern. "Pro javaScript Design Patterns" is a classic book, but the examples in it are cool, so I will summarize my understanding based on the code I have written at work. If there is a deviation in my understanding, please ignore it.

Singleton Mode

The Singleton mode is defined to generate a unique instance of a class, but js itself is a "classless" language. Many articles about js design patterns use {} As a Singleton, which barely makes sense. Because there are many methods to generate objects in js, let's look at another more meaningful Singleton.

There is a common requirement that a mask layer should be displayed on the page when you click a button. For example, when you click web.qq.com to log on.

The code for generating the gray background mask layer is well written.

 
 
  1. var createMask = function(){ 
  2.    return document.body.appendChild(  document.createElement(div)  ); 

 
 
  1. $( 'button' ).click( function(){ 
  2.    Var mask  = createMask(); 
  3.    mask.show(); 
  4. }) 

The problem is that this mask layer is globally unique, so a new div will be created every time createMask is called. Although it can be removed from the hidden mask layer, this is obviously unreasonable.

Let's look at the second solution. Create the div at the beginning of the page and reference it with a variable.

 
 
  1. var mask = document.body.appendChild( document.createElement( ''div' ) ); 
  2. $( ''button' ).click( function(){ 
  3.    mask.show(); 
  4. } ) 

In this way, only one div of the mask layer will be created on the page, but another problem arises. Maybe we will never need this mask layer, which will waste a div, any operations on dom nodes should be very stingy.

If you can use a variable. To determine whether a div has been created?

 
 
  1. var mask; 
  2. var createMask = function(){ 
  3. if ( mask ) return mask; 
  4. else{ 
  5. mask = document,body.appendChild(  document.createElement(div)  ); 
  6. return mask; 

It looks good. Here we have completed a function that generates a single column object. Let's take a closer look at what is wrong with this code.

First, this function has some side effects. The function changes the reference of the external variable mask. In a multi-person Collaboration Project, createMask is an insecure function. on the other hand, the global variable mask is not required. let's make some improvements.

 
 
  1. var createMask = function(){ 
  2.   var mask; 
  3.   return function(){ 
  4.        return mask || ( mask = document.body.appendChild( document.createElement('div') ) ) 
  5.   } 
  6. }() 

A simple closure is used to wrap the variable mask. At least for the createMask function, it is closed.

The Singleton mode may be too simple. it is true that some design patterns are very simple. Even if you have never paid attention to the concept of design patterns, some design patterns can be used in the code at ordinary times. just like many years ago, when I understood what the old man's stroller was, I also thought about Nima's old man's stroller.

The 23 Design Patterns in GOF are also existing and used repeatedly in software development. if the programmer does not realize that he has used some models, he may miss a more appropriate design next time (this article comes from the songben luhong program world).

The previous Singleton still has shortcomings. It can only be used to create a mask layer. If I need to write another function to create a unique xhr object, what should I do? Can you find a general singleton package.

In js, the function is the first type, which means that the function can also be passed as a parameter. See the final code.

 
 
  1. var singleton = function( fn ){ 
  2.     var result; 
  3.     return function(){ 
  4.         return result || ( result = fn .apply( this, arguments ) ); 
  5.     } 
  6. var createMask = singleton( function(){ 
  7. return document.body.appendChild( document.createElement('div') ); 
  8.  }) 

Use a variable to save the first return value. If it has been assigned a value, the variable will be returned first in future calls. the code that actually creates the mask layer is passed to the singleton package through the callback function. this method is actually called the bridge mode. for the bridge mode, put it a little later.

However, the singleton function is not perfect. It always requires a variable result to store the reference of div. Unfortunately, the functional features of js are not enough to completely eliminate the Declaration and statements.


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.