JavaScript design Pattern Single example (singleton) mode

Source: Internet
Author: User

The singleton mode restricts the number of instances of a class to be instantiated only once. Singleton mode, where the instance does not exist, you can create a new instance of the class by creating a class with a method, and if the instance already exists, it simply returns the reference to the object. Singleton is different from a static class, it can be deferred instantiation.

1. Object literal implementation

There are many ways to implement singleton patterns in JavaScript, the simplest of which is object literals.

var singleton={     Name: "Vuturn",     showname:function () {          console.log (this.name);         }  }

Of course, you can also extend the object, you can add private members and methods, and use closures to encapsulate variables and methods inside them. Exposes public methods and variables by returning an object.

2. Using closures to implement

  var mysingleton= (function () {        var instance;        function init () {            function Privatemethod () {                Console.log ("This is Private");            }            var privatevariable= "This is Privart too!";            return {             publicmethod:function () {                 Console.log ("This was public!");             },                Publicproperty: "This is Public too! "            }        }        return {            getinstance:function () {                if (!instance) {                    instance=init ();                }                return instance;}}    ) ();

3. Using the new operator

We want to achieve the following effects:


var uni=new Universe (),    uni2=new Universe (); uni==uni2;

The Uni object is created the first time the constructor is called, and the same uni object is returned directly at the second (or more) time. This is why uni===uni2, because it refers to a reference to the same object.

So how do you implement this pattern in JavaScript?

The Universe object is required to cache the This object so that the same object can be created and returned the second time it is called. There are a number of ways to achieve this goal.

(1) You can use global variables to store the instance. This is not recommended, however, because global variables are easily overwritten.

(2) The instance can be cached in the static properties of the constructor. The only drawback to this simple approach is that static properties are publicly accessible properties that can be modified by external code.

(3) The instance can be wrapped in a closure. This guarantees the private nature of the instance and guarantees that the instance will not be modified by code other than the constructor.

The second and third implementations are shown here:

Instances in a static property

function  Universe () {      if (typeof universe.instance = = = = "Object") {          return universe.instance;      }      this.start_time=0;      Universe.instance=this;      return this;  }    var uni=new Universe ();    var uni2=new Universe ();  Console.log (  uni===uni2);

Instances in closures

function  Universe () {     var instance=this;      this.start_time=0;      universe= function () {          return instance;      }  }    var uni=new Universe ();    var uni2=new Universe ();  Console.log (  uni===uni2);


The above code returns the this pointer the first time it is called, when the constructor has been rewritten and returned to instance at a later call. The disadvantage of this pattern is that it overrides the constructor and loses all attributes added to it between the initial definition and the redefined moment. In this particular case, any object added to the Universe prototype will not have an active link to the friend's original implementation.

Take a look at the following tests:

    Universe.prototype.nothing=true;    var uni=new Universe ();    Universe,prototype.everything=true;    var uni2=new Universe ();    uni.nothing;  True    uni2.nothing;  True    uni.everything;//undefined    uni2.everything;//undefined    uni.constructor.name;  Universe    Uni.constructor===universe;  False

The reason that Uni.constructor is no longer the same as the Universe () constructor is because Uni.constructor still points to the original constructor.

If you need prototypes and constructor pointers to run as expected, you can do so in the following ways:


function  Universe () {     var instance;      universe= function () {          return instance;      }      Rewrite prototype      universe.prototype=this;      Instance=new Universe ();      Instance.constructor=universe;      instance.start_time=0;      return instance;  }   Universe.prototype.nothing=true;    var uni=new Universe ();    Universe.prototype.everything=true;    var uni2=new Universe ();    Console.log (UNI===UNI2);    Console.log (UNI);    Console.log (UNI2);    Console.log (Uni.constructor);











Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaScript design Pattern Single example (singleton) mode

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.