Home  >  Article  >  Web Front-end  >  In-depth understanding of JavaScript series (25): Detailed explanation of the singleton pattern of design patterns_Basic knowledge

In-depth understanding of JavaScript series (25): Detailed explanation of the singleton pattern of design patterns_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:11:30876browse

Introduction

Starting from this chapter, we will gradually introduce the implementation of various design patterns used in JavaScript. Here I will not introduce too much about the theory of the pattern itself, but will only focus on the implementation. OK, it’s officially started.

In the eyes of traditional development engineers, a singleton is to ensure that a class has only one instance. The implementation method is generally to first determine whether the instance exists. If it exists, return it directly. If it does not exist, create it and return it. This ensures A class has only one instance object. In JavaScript, a singleton acts as a namespace provider, providing a unique access point to the object from the global namespace.

Text

In JavaScript, there are many ways to implement singletons. One of the simplest ways is to use object literals, which can contain a large number of properties and methods:

Copy code The code is as follows:

var mySingleton = {
Property1: "something",
Property2: "something else",
Method1: function () {
console.log('hello world');
}
};

If you later extend this object, you can add your own private members and methods, and then use closures to encapsulate these variable and function declarations inside it. Expose only the public members and methods you want to expose. The sample code is as follows:
Copy code 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 'something private'
console.log(single.publicVar); // Output 'the public can see this!'

The above code is very good, but what if we want to initialize it only when it is used? In order to save resources, we can initialize these codes in another constructor, as follows:

Copy code The code is as follows:

var Singleton = (function () {
var instantiated;
Function init() {
/*Define singleton code here*/
         return {
              publicMethod: function () {
console.log('hello world');
            },
             publicProperty: 'test'
        };
}

return {
         getInstance: function () {
                if (!instantiated) {
                         instantiated = init();
            }
              return instantiated;
}
};
})();

/*Call public methods to get instances:*/
Singleton.getInstance().publicMethod();

We now know how to implement a singleton, but in what scenarios is a singleton best used? In fact, singletons are generally used to coordinate various modes of communication between systems. The following code is a best practice for a singleton:

Copy code The code is as follows:

var SingletonTester = (function () {

//Parameters: a set of parameters passed to the singleton
Function Singleton(args) {

//Set the args variable to the received parameters or empty (if not provided)
var args = args || {};
//Set the name parameter
This.name = 'SingletonTester';
//Set the value of pointX
This.pointX = args.pointX || 6; //Get it from the received parameters, 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 to get the 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:

Copy code 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 returns this
}

//Test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true

Method 2:

Copy code The code is as follows:

function Universe() {

// cached instance
var instance = this;

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

// Override 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:

Copy code The code is as follows:

function Universe() {

// Cache instance
var instance;

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

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

// Example
Instance = new Universe();

// Reset 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:

Copy code 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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn