Learn about JavaScript Design Patterns (single case mode) _javascript tips

Source: Internet
Author: User
Tags closure

Singleton schema Definition: guarantees that a class has only one instance and provides a global access point to access it.

A single case pattern is a common pattern, with some objects that we often need only one, such as thread pooling, global caching, and browser window objects. In JS Development, the use of single case mode is also very extensive. Imagine that when we click on the login button, a login box appears on the page, and the floating window is unique, and the window will only be created once, no matter how many times the login button is clicked. Therefore, this login window is suitable for single case mode.

1, a single case mode of use of the scene

Before using a pattern, we'd better be aware of the use scenario for this pattern. With so long a single case pattern, unexpectedly completely did not know! What are the advantages of using it specifically?

1). You can use it to divide the namespaces (this is often used)

2. Use branch technology to encapsulate the differences between browsers (this is really useless, quite fresh)

3. With the help of single case mode, the code can be organized more consistent, easy to read and maintain (this is also used)

2, the most basic single case mode

The simplest single example is actually a literal amount of an object. It organizes a group of methods and attributes that have a certain correlation.

var Singleton = {
  attr1:true, 
  attr2:10,
  method1:function () {
    alert (' I am Method 1 ');
  },
  Method2:fu Nction () {
    alert (' I am Method 2 ');
  }
;

This object can be modified. You can add properties and methods. You can also delete an existing member with the delete operator. This actually violates the principle of object-oriented design: A class can be extended, but should not be modified. If certain variables need to be protected, they can be defined in a closure.

Object literals are just one way to create a single example. Not all object literals are a single example, and those that are just used to mimic associative arrays or to hold data are clearly not examples of objects.

3, the use of closures to create a single case

Closure main purpose to protect the data

Namespace
var BHX = {};
BHX. Singleton = (function () {
  //Add own Private member
  var a1 = true;
  var a2 = ten;
  var f1 = function () {
    alert (' F1 ');
  }
  var F2 = function () {
    alert (' F2 ');
  }        
  Assign the execution result in the block-level scope to my single Instance object return
  {
      attr1:a1, 
      attr2:a2,
      method1:function () {
        F1 (); c19/>},
      method2:function () {return
        F2 ();}}            
  ;
}) ();

Alert (BHX. SINGLETON.ATTR1);
BHX. Singleton.method1 ();

This single example model is also called module mode, which means that it can organize a batch of related methods and attributes into modules and play the role of dividing namespaces.

4, the single case mode is used to divide the namespace

1), prevent the modification of the global Declaration

/*using a namespace*/

var BHX = {};
BHX. Singleton = {
  attr1:true, 
  attr2:10,
  method1:function () {
    alert (' I am Method 1 ');
  },
  method2: function () {
    alert (' I am Method 2 ');
  }        
;
BHX. SINGLETON.ATTR1;
var attr1 = false;

In this way, even if we declare the same variables outside, we can prevent ATTR1 from being modified to some extent.

2), to prevent other source code changes

JavaScript code on a Web page is now often more than just a source, library code, ad code, and badge code. To avoid conflicts with your own code, you can define an object that contains all of your code.

var XGP = {};
Xgp.common = {//a singleton with Common methods used from all objects and
  modules
}
XGP. Errorcodes = {
  //an object literal used to store data
}
XGP. Pagehandler = {
  //a singleton with page specific methods and attributes.
}

3), as a special code encapsulation

In a Web site with many Web pages, some code is used by all pages, and they are usually stored in separate files, while others are specific to a Web page and are not used elsewhere. It is a good idea to wrap the two codes separately in your own single Instance object.

We often use JavaScript to add functionality to our forms. For the sake of smooth degradation, it is often first to create a plain HTML Web page that does not rely on JavaScript to complete the task using the normal submission mechanism.

 XGP.  Regpage = {form_id: ' Reg-form ', output_id: ' Reg-result ', Handlesubmit:function (e) {e.preventdefault ();//stop
    The normal form submission var data = {}; var inputs = XGP.

    RegPage.formEl.getElementByTagName (' input ');
    For (var i=0, len=inputs.length; i<len; i++) {Data[inputs[i].name] = Inputs[i].value; } XGP.
  Regpage.sendregistration (data); Sendregistration:function (data) {//make A XHR request and call Displayresult () at response is recieved.
  . }, Displayresult:function (response) {XGP.
  RegPage.outputEl.innerHTML = response; }, Init:function () {XGP. Regpage.formel =$ (XGP.
    REGPAGE.FORM_ID); XGP. Regpage.outputel = $ (XGP.
    REGPAGE.OUTPUT_ID); Hijack the form submission addevent (XGP. Regpage.formel, ' Submit ', XGP.
  Regpage.handlesubmit); }//invoke initialization method after the page load Addloadevent (XGP.

Regpage.init); 

5, inert single case

The single example pattern mentioned earlier has one thing in common: the single object is created when the script is loaded. For a resource-intensive or configuration-expensive single case, it is more reasonable to postpone its instantiation until it is necessary to use it.

This technique is lazy loading (lazy loading).

The implementation steps are as follows:

1. Move all your code into the constructor method

2. Full control of the timing of the call (exactly what getinstance is going to do)

Xgp.lazyloading = (function () {
  var uniqinstance;

  function constructor () {
    var attr = false;
    Function method () {

    } return

    {
      attrp:true,
      methodp:function () {

      }}
    ' return

  {
    getinstance:function () {
      if (!uniqinstance) {
        uniqinstance = constructor ();
      }
      Return uniqinstance}
    }
) ();

6. Branch Technology

A branch is a technique used to encapsulate differences between browsers in a dynamic method that is set up during a run.

Branch Single example (judge the branch of the program < browser differences detection >)
var Ext = {};
var def = false;
Ext.more = (function () {
  var obja = {    //Firefox browser internal configuration
      attr1: ' FF property 1 '
      //property 1 
      //Property 2 
      //Method 1 
      // Method 2
  };
  var objb = {    //IE some of the internal configuration
      attr1: ' IE property 1 '
      //property 1 
      //Property 2 
      //Method 1 
      //Method 2             
  };
  Return (Def) obja:objb;
}) ();
alert (EXT.MORE.ATTR1);

For example, if you want to use XHR frequently in your site, run the browser sniffing code again every time you call, which can be a serious inefficiency. A more efficient approach is to determine the browser-specific code once the script is loaded. This is exactly what branching technology does. Of course, branching technology is not always a more efficient choice, with only one branch in two or more branches being used, and other branches consuming memory.

When considering whether to use branching technology, you must weigh the benefits of shortening time and consuming more memory.

The following uses branch technology to implement XHR:

var XHR = (function () {
  var standard = {
    createxhrobj:function () {return
      new XMLHttpRequest ();
    }
  };
  var activexnew = {
    createxhrobj:function () {return
      new ActiveXObject (' msxml2.xmlhttp ');
    }
  ;
  var activexold = {
    createxhrobj:function () {return
      new ActiveXObject (' microsoft.xmlhttp ');
    }
  ;

  var testobj;
  try{
    testobj = Standard.createxhrobj ();
    return testobj;
  } catch (e) {
    try{
      testobj = Activexnew.createxhrobj ();
      return testobj;
    } catch (e) {
      try{
        testobj = Activexold.createxhrobj ();
        return testobj;
      } catch (e) {
        throw new Error (' No XHR object found in this environment. '}}
      }
) ();

7, the malpractice of the single case model

With so much knowledge about the single case, let's look at its drawbacks.

Because a single case pattern provides a single point of access, it can cause strong coupling between modules. Therefore, it is not conducive to unit testing.

In summary, the use of a single example is left to define namespaces and implement branching methods.

Through seven different aspects of the introduction of the single example mode, we are not the single case mode has a more in-depth understanding, I hope this article can help everyone.

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.