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:
/* 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:
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:
//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:
// 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:
// 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:
// 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:
(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