meaning
As the name implies, singletons literally mean singletons, and can also be understood to guarantee that a class has only one instance and provide a global access point to access it.Copy the code
Train of thought
When creating an object, check whether the object exists globally. If so, return the object. If not, create a new instance and return itCopy the code
Js implementation
- ES5 implementation
var Single = (function() {
var instance = null;
function Single(name) {
this.name = name;
}
return function(name){
if(! instance) { instance =new Single(name);
}
returninstance; }; }) ();var oA = new Single('hi');
var oB = new Single('hello');
console.log(oA===oB);
Copy the code
The first call to the constructor stores an instance with a closure, and subsequent calls return instance directly
- ES6 implementation
class Singleton {
constructor(name) {
this.name = name;
this.instance = null;
}
static getInstance(name) {
if(!this.instance) {
this.instance = new Singleton(name);
}
return this.instance; }}var oA = Singleton.getInstance('hi');
var oB = Singleton.getInstance('hisd');
console.log(oA===oB);
Copy the code
A class is the prototype of an instance. All methods defined in a class are inherited by the instance. If you prefix a method with the static keyword, that method is not inherited by the instance.
- Application of singleton pattern: only one common instance object is required globally, for example:
-
Log in to the popover component
-
A music playback program, if the user opened a music, and want to open a music, then the previous playback interface will automatically close, switch to the current playback interface. These are all application scenarios for the singleton pattern.
-
For any website, click the login button, and only one login box will pop up. Even if you click the login button again, another pop-up box will not pop up
-