Understanding of the javascript Singleton Mode

Source: Internet
Author: User

Understanding of the javascript Singleton Mode
Understanding the meaning of Singleton mode in singleton mode is to ensure that a class has only one instance and provide a global access point to it. The method is to use a variable to indicate whether an object has been created for a class. If an object has been created, the newly created object is directly returned when you obtain the instance of this class next time, otherwise, an object is created. This ensures that a class has only one instance object. For example, the following code is a simple Singleton code example:

Var Singleton = function (name) {this. name = name; // use the instance flag to determine whether an instance is created this. instance = null;}; Singleton. prototype. getName = function () {console. log (this. name) ;}; Singleton. getInstance = function (name) {if (! This. instance) {this. instance = new Singleton (name);} return this. instance ;}

 

Now we can use the following code for initialization: var a = Singleton. getInstance ("aa"); var B = Singleton. getInstance ("bbb"); console. log (a); console. log (B); print as follows: continue the following test:
console.log(a === b);  // truea.getName();  // aab.getName();  // aaa.test = "test";console.log(b.test); // test 

 

Test the code above, we can see that it is first instantiated, passed aa to the name parameter, saved to the variable, and then called the getIstance method again for the second time, because the instance already exists, so use the object created for the first time, so a = B is true,. getName () and B. the getName () value is printed as aa. You can write the code as follows:
var Singleton = function(name){    this.name = name; };Singleton.prototype.getName = function(){    console.log(this.name);};Singleton.getInstance = (function(){    var instance = null;    return function(name){        if(!instance) {            instance = new Singleton(name);        }        return instance;    }})(); 

 

Return to the top and use proxy to implement Singleton mode. For example, if I want to create a div element on the page, the following code uses proxy to implement Singleton mode:
var CreateDiv = function(html) {    this.html = html;    this.init();};CreateDiv.prototype.init = function(){    var div = document.createElement("div");    div.innerHTML = this.html;    document.body.appendChild(div);};var ProxySingletonCreateDiv = (function(){    var instance;    return function(html) {        if(!instance) {            instance = new CreateDiv(html);        }        return instance;    }})();var a = new ProxySingletonCreateDiv("aa");var b = new ProxySingletonCreateDiv("bbb");console.log(a === b); // true 

 

Code above: we moved the logic for managing the singleton to the ProxySingletonCreateDiv function. The CreateDiv function is a common function, that is, the method for creating the div, then the logic of the specific management Singleton is handed over to the ProxySingletonCreateDiv function; the meaning of understanding the inertia Singleton at the top is that the object instance is created only when necessary, in the previous section, we talked about creating an instance when the page is loaded. For example, the div in a pop-up window on the page has many other display elements, if some users do not click the pop-up window, some dom nodes are created during page initialization. If we use the inert Singleton, we can create dom nodes only when the user needs them. First, let's see how to create a div pop-up window when page loading is complete. This pop-up window is hidden at the beginning. It is displayed only when you click a button. The Code is as follows: <button id = "btn"> click me </button>
Var CreateDiv = (function () {var div = document. createElement ('div '); div. innerHTML = "I'm a pop-up window test"; div. style. display = "none"; document. body. appendChild (div); return div ;}) (); document. getElementById ("btn "). onclick = function () {CreateDiv. style. display = "block" ;}; the inert code is as follows: var CreateDiv = function () {var div = document. createElement ('div '); div. innerHTML = "I'm a pop-up window test"; div. style. display = "none"; document. body. appendChild (div); return div ;}; document. getElementById ("btn "). onclick = function () {var createDiv = CreateDiv (); createDiv. style. display = "block ";};

 

As shown in the above Code, when we click the button, we create the div element, but each time we click it, we have to create the element, which is also unreasonable. However, in the above code, we can use a variable to determine whether a div pop-up window has been created; as shown below:
Var CreateDiv = (function () {var div; return function () {if (! Div) {div = document. createElement ('div '); div. innerHTML = "I'm a pop-up window test"; div. style. display = "none"; document. body. appendChild (div) ;}return div ;}) (); document. getElementById ("btn "). onclick = function () {var createDiv = CreateDiv (); createDiv. style. display = "block ";};

 

Back to the top to write a common inertia ticket, for example, although the Code has completed the inertia Singleton, but there are some problems; violation of the single responsibility principle; for example, the logic for creating an object and managing a singleton is placed inside the CreateDiv object, and the code is not abstracted. For example, the above is to create a div element, however, if I want to create a script element or an iframe element in the future, we need to copy the code above and rewrite it. For example, if I follow the above method to create a div, now, if we need to create another iframe element, the code should be changed to the following:
var createIframe = (function(){    var iframe;    return function(){        if(!iframe) {            iframe = document.createElement('iframe');            iframe.style.display = 'none';            document.body.appendChild(iframe);        }        return iframe;    }})();

 

We are definitely considering how to make the above Code public, so that we can implement abstract code. The logic code for managing Singleton can actually be abstracted. This logic is the same, use a variable to indicate whether an object has been created. If yes, return the created object directly next time. We can encapsulate these logics in the getSingle function, the method for creating an object fn is used as a parameter to dynamically pass in the getSingle function; the following code:
var getSingle = function(fn){    var result;    return function(){        return result || (fn.apply(this,arguments));    };};

 

The following describes how to create a div using getSingle:
Var CreateDiv = function () {var div = document. createElement ('div '); div. innerHTML = "I'm a pop-up window test"; div. style. display = "none"; document. body. appendChild (div); return div ;}; // create a singlediv var createSingleDiv = getSingle (CreateDiv); document. getElementById ("btn "). onclick = function () {// call the singleton method var createDiv = createSingleDiv (); createDiv. style. display = "block ";};

 

For example, to create an iframe, the Code is as follows:
Var createSingleIframe = getSingle (function () {var iframe = document. createElement ('iframe'); document. body. appendChild (iframe); return iframe;}); document. getElementById ("btn "). onclick = function () {// call the singleton method var createSingleIframe = createSingleIframe (); createSingleIframe. src = "http://cnblogs.com ";};

 

Back to the top Singleton mode, there are some objects that we only need, such as the pop-up window, global cache, and browser window objects. In Singleton mode, only one instance is created and only one instance is available,
 var a = Singleton.getInstance("aa");var b = Singleton.getInstance("bbb");console.log(a === b);  // truea.getName();  // aab.getName();  // aa

 

The first request is aa, and the second request is bbb. Why does the request output aa after the getName () method is called, this is where the singleton mode creates only one instance;

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.