JavaScript design mode Item 6-singleton mode Singleton

Source: Internet
Author: User

Definition of a singleton pattern: guarantees that a class has only one instance and provides a global access point to access it.

Singleton mode is a common pattern, and there are some objects that we often only need one, such as a thread pool, a global cache, a browser window object. In JS Development, the use of singleton patterns is also very extensive. Imagine that when we click the login button, a login box will appear on the page, and this floating window will only be created once, no matter how many times you click the login button. Therefore, this login window is suitable for single-case mode.

1, the use of single-case mode of the scene

Before using a pattern, we'd better know the usage scenario for this pattern. With so long a single case pattern, unexpectedly completely do not know! What are the specific benefits of using it?

    • 1. You can use it to divide the namespace (which is often used)

    • 2. Using branching technology to encapsulate differences between browsers (this is really useless, very fresh)

    • 3. With the help of the singleton mode, the code can be organized more consistently, easy to read and maintain (this has been used too)

2, the most basic single-case mode

The simplest single case is actually an object literal. It organizes a number of methods and properties that are related to each other.

var Singleton = {    true ,     10 ,    function(){        alert(‘我是方法1‘);    },    function(){        alert(‘我是方法2‘);    }};

This object can be modified. You can add properties and methods. You can also delete an existing member by using the delete operator. This actually violates the principle of object-oriented design: classes can be extended, but should not be modified. if certain variables need to be protected, they can be defined in closures.

Object literals are just one way to create a singleton. Also not all object literals are singleton, and the object literals that are simply used to mimic associative arrays or accommodate data are obviously not singleton.

3, borrow closure to create a single case

Closure of the main target to protect data

//NamespacevarBHX = {}; BHX. Singleton = ( function(){    //Add your own private members    varA1 =true;varA2 =Ten;varF1 = function(){Alert' F1 '); }varF2 = function(){Alert' F2 '); }//Assign the execution result in the block scope to my singleton object    return{attr1:a1, ATTR2:A2, method1: function(){                returnF1 (); }, Method2: function(){                returnF2 (); }                           } ;}) (); alert (BHX. SINGLETON.ATTR1); BHX. Singleton.method1 ();

This singleton mode, also known as module mode , means that it can organize a batch of related methods and attributes into modules and play the role of dividing the namespace.

4. Singleton mode for dividing namespaces

1, prevent the modification of the global Declaration

/*using a namespace*/var BHX = {};BHX.Singleton = {    true ,     10 ,    function(){        alert(‘我是方法1‘);    },    function(){        alert(‘我是方法2‘);    }               };BHX.Singleton.attr1;varfalse;

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

2. Prevent modification of other source code

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

var XGP = {};XGP.Common = {    //withbyand modules}XGP.ErrorCodes = {    //An object literal used to store data}XGP.PageHandler = {    //withand attributes.}

3, as a special code package

In Web sites with many Web pages, some code is used for all pages, they are usually stored in separate files, and some are specific to a Web page and are not used elsewhere. It's a good idea to wrap the two code in your own singleton.

We often use JavaScript to add functionality to a form. For the sake of smooth degradation, it is common to create a plain HTML Web page that does not rely on JavaScript to complete tasks using the normal commit mechanism.

XGP. Regpage = {form_id:' Reg-form ', output_id:' Reg-result ', Handlesubmit: function(e){E.preventdefault ();//stop The normal form submission        vardata = {};varInputs = XGP. RegPage.formEl.getElementByTagName (' input '); for(varI=0, Len=inputs.length; i<len;        i++) {Data[inputs[i].name] = Inputs[i].value; } XGP.    Regpage.sendregistration (data); }, Sendregistration: function(data){        //make an XHR request and call Displayresult () when 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 submissionAddevent (XGP. Regpage.formel,' Submit ', XGP.    Regpage.handlesubmit); }}//invoke initialization method after the page loadAddloadevent (XGP. Regpage.init);
5. Inert single case

The singleton pattern mentioned earlier has one more thing in common: Singleton objects are created when the script is loaded. For a resource-dense or configuration-expensive single case, it is more reasonable to defer its instantiation until it is needed.

This technique is lazy loading (lazy loading).

The implementation steps are as follows:

    • 1. Move all code into the constructor method

    • 2. Full control of the timing of the call (exactly what getinstance will do)

Xgp.lazyloading = ( function(){    varUniqinstance; function constructor(){        varattr =false; function method(){}return{ATTRP:true, METHODP: function(){}        }    }return{getinstance: function(){            if(!uniqinstance)            {uniqinstance = constructor (); }returnUniqinstance; }    }})();
6. Branch Technology

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

//Branch Singleton (judging the branch of the program < The detection of browser differences >)varExt = {};vardef =false; Ext.more = ( function(){    varObja = {//Some configuration inside Firefox browserATTR1:' ff attribute 1 '            //attribute 1            //attribute 2            //Method 1            //Method 2} ;varOBJB = {//Some configuration inside IE browserATTR1:' IE attribute 1 '            //attribute 1            //attribute 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, you'll run the browser sniffing code again every time you call it, which can be a serious lack of efficiency. A more efficient approach is to determine the browser-specific code once the script is loaded. This is exactly what branch technology does. Of course, branching is not always a more efficient option, with only one branch in two or more branches being used, and other branches taking up memory.

When considering whether to use branch technology, it is necessary to weigh the pros and cons of shortening the time and taking up more memory.

The following XHR are implemented using branch technology:

varXHR = ( function(){    varStandard = {createxhrobj: function(){            return NewXMLHttpRequest (); }    };varActivexnew = {createxhrobj: function(){            return NewActiveXObject (' Msxml2.xmlhttp '); }    };varActivexold = {createxhrobj: function(){            return NewActiveXObject (' Microsoft.XMLHTTP '); }    };varTestobj;Try{testobj = Standard.createxhrobj ();returnTestobj; }Catch(e) {Try{testobj = Activexnew.createxhrobj ();returnTestobj; }Catch(e) {Try{testobj = Activexold.createxhrobj ();returnTestobj; }Catch(e) {Throw New Error(' No XHR object found in this environment. '); }        }    }})();
7, the disadvantage of the single case model

Having learned so much about a single case, let's look at its drawbacks.

Because Singleton mode provides a single point of access, it is possible to cause strong coupling between modules. Therefore, it is not conducive to unit testing.

In summary, the Singleton is left to define namespaces and implement branching methods for these purposes.

Reference:
JCHENJS design mode-Singleton mode

Copyright NOTICE: This article is the original article, reproduced please specify: http://blog.csdn.net/i10630226

JavaScript design mode Item 6-singleton mode Singleton

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.