In-depth understanding of the JavaScript series (25): detailed description of the Singleton mode of design patterns _ basic knowledge

Source: Internet
Author: User
This article mainly introduces a deep understanding of the JavaScript series (25): a detailed explanation of the Singleton mode of the design mode. This article provides implementation methods of multiple Singleton modes. For more information, see Introduction

Starting from this chapter, we will gradually introduce the implementation of various design patterns used in JavaScript. here I will not introduce the theory of the pattern too much, but will only focus on implementation. OK.

In the eyes of traditional development engineers, Singleton is to ensure that there is only one instance for a class. the implementation method is to first determine whether the instance exists or not. if the instance exists, it is directly returned. if the instance does not exist, it is created and then returned, this ensures that a class has only one instance object. In JavaScript, a singleton acts as a namespace provider and provides a unique access point from the global namespace to access this object.

Body

In JavaScript, there are many ways to implement Singleton. one of the simplest ways is to use the object literal method, which can contain a large number of attributes and methods:

The code is as follows:


Var mySingleton = {
Property1: "something ",
Property2: "something else ",
Method1: function (){
Console. log ('Hello World ');
}
};


If you want to extend this object in the future, you can add your own private members and methods, and then use closures to encapsulate these variables and function declarations within it. Only expose the public members and methods you want to expose. the sample code is as follows:

The code is as follows:


Var mySingleton = function (){

/* Declare private variables and methods here */
Var privateVariable = 'something private ';
Function showPrivate (){
Console. log (privateVariable );
}

/* Public variables and methods (private variables and methods can be accessed )*/
Return {
PublicMethod: function (){
ShowPrivate ();
},
PublicVar: 'The public can see this! '
};
};

Var single = mySingleton ();
Single. publicMethod (); // output 'somethprivate'
Console. log (single. publicVar); // output 'The public can see this! '

The above code is good, but if we want to initialize it only when it is used, what should we do? To save resources, we can initialize the code using another constructor, as shown below:

The code is as follows:


Var Singleton = (function (){
Var instantiated;
Function init (){
/* The Singleton code is defined here */
Return {
PublicMethod: function (){
Console. log ('Hello World ');
},
PublicProperty: 'test'
};
}

Return {
GetInstance: function (){
If (! Instantiated ){
Instantiated = init ();
}
Return instantiated;
}
};
})();

/* Call the public method to obtain the instance :*/
Singleton. getInstance (). publicMethod ();

I know how to implement the singleton, but what kind of scenarios is better for Singleton? In fact, Singleton is generally used for communication and coordination between systems in various modes. the following code is a singleton best practice:

The code is as follows:


Var SingletonTester = (function (){

// Parameter: a set of parameters passed to the Singleton.
Function Singleton (args ){

// Set the args variable to the received parameter or to null (if not provided)
Var args = args || {};
// Set the name parameter
This. name = 'singletontester ';
// Set the pointX value
This. pointX = args. pointX | 6; // get it from the received parameter, or set it to the default value.
// Set the value of pointY
This. pointY = args. pointY | 10;

}

// Instance container
Var instance;

Var _ static = {
Name: 'singletontester ',

// Method for obtaining an instance
// Return Singleton instance
GetInstance: function (args ){
If (instance === undefined ){
Instance = new Singleton (args );
}
Return instance;
}
};
Return _ static;
})();

Var singletonTest = SingletonTester. getInstance ({pointX: 5 });
Console. log (singletonTest. pointX); // output 5

Other implementation methods

Method 1:

The code is as follows:


Function Universe (){

// Determine whether an instance exists
If (typeof Universe. instance === 'object '){
Return Universe. instance;
}

// Other content
This. start_time = 0;
This. bang = "Big ";

// Cache
Universe. instance = this;

// Implicitly return this
}

// Test
Var uni = new Universe ();
Var uni2 = new Universe ();
Console. log (uni === uni2); // true

Method 2:

The code is as follows:


Function Universe (){

// Cached instance
Var instance = this;

// Other content
This. start_time = 0;
This. bang = "Big ";

// Rewrite the constructor
Universe = function (){
Return instance;
};
}

// Test
Var uni = new Universe ();
Var uni2 = new Universe ();
Uni. bang = "123 ";
Console. log (uni === uni2); // true
Console. log (uni2.bang); // 123

Method 3:

The code is as follows:


Function Universe (){

// Cache instance
Var instance;

// Reconstructor
Universe = function Universe (){
Return instance;
};

// Post-processing prototype attributes
Universe. prototype = this;

// Instance
Instance = new Universe ();

// Reset the constructor pointer
Instance. constructor = Universe;

// Other functions
Instance. start_time = 0;
Instance. bang = "Big ";

Return instance;
}


// Test
Var uni = new Universe ();
Var uni2 = new Universe ();
Console. log (uni === uni2); // true

// Add prototype attributes
Universe. prototype. nothing = true;

Var uni = new Universe ();

Universe. prototype. everything = true;

Var uni2 = new Universe ();

Console. log (uni. nothing); // true
Console. log (uni2.nothing); // true
Console. log (uni. everything); // true
Console. log (uni2.everything); // true
Console. log (uni. constructor === Universe); // true

Method 4:

The code is as follows:


Var Universe;

(Function (){

Var instance;

Universe = function Universe (){

If (instance ){
Return instance;
}

Instance = this;

// Other content
This. start_time = 0;
This. bang = "Big ";
};
}());

// Test code
Var a = new Universe ();
Var B = new Universe ();
Alert (a = B); // true
A. bang = "123 ";
Alert (B. bang); // 123

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.