It 's written in front .
The singleton pattern is well known because it limits the number of instances of a class to be instantiated only once. In the classical sense, the singleton mode can create a new instance of the class by creating a class in a way that does not exist in the instance, and it simply returns a reference to the object if the instance already exists.
Singleton are different from static classes (or objects) because we can postpone their initialization, usually because they require some information that may not be available during initialization, and that does not provide a convenient way to retrieve code that is not aware of previous references. This is because it is neither an object nor a "class" returned by a singleton;
Think about Why the closure variable is not actually a closure , but the function scope that provides the closure is the closure. In JavaScript, Singleton acts as a shared resource namespace, isolating code implementations from the global namespace, providing a single point of access for functions. here's an example.
var mysingleton= (function () {//instance keeps singleton a reference to Var instance; function init () {//singleton//private method and variable function Privatemethod () {console.log ("I am pri
Vate ");
var privatevariable= "I am also private";
var privaterandomnumber=math.random ();
return{//Public method and variable publicmethod:function () {Console.log ("the" "the" Can-I-me!); }, Publicproperty: "I am also public", Getrandomnumber:function () {RET
Urn Privaterandomnumber;
}
};
return{//Gets an instance of singleton, returns if it exists, creates a new instance if it does not exist getinstance:function () {if (!instance) {
Instance=init ();
return instance;
}
}
})();
var mybadsingleton= (function () {//instance holds a reference to the singleton var instance;
function init () {//singleton var privaterandomnumber=math.random (); return{getrandomnumber:function () {return privaterandomnumber;
}
};
return{//Each time a new instance is created Getinstance:function () {instance=init ();
return instance;
}
};
})();
var singlea=mysingleton.getinstance ();
var singleb=mysingleton.getinstance (); Console.log (Singlea.getrandomnumber () ===singleb.getrandomnumber ());
True var badsinglea=mybadsingleton.getinstance ();
var badsingleb=mybadsingleton.getinstance (); Console.log (Badsinglea.getrandomnumber ()!==badsingleb.getrandomnumber ()); True
Analysis
Well, with so much code in writing, let's start with a question-what makes Singleton the global access point for an instance (usually through mysingleton.getinstance ())?
Because we don't (at least in the static language) call the new Mysingleton () directly. However, this is possible in JavaScript. the applicable scene
1. When a class can have only one instance and the customer can access it from a well-known access point.
2. The unique instance should be extensible through subclasses, and the customer should be able to use an extended instance without changing the code. deferred execution
Let's look at the following code:
Mysingleton.getinstance=function () {
if (this._instance==null) {
if (Isfoo ()) {
this._instance=new Foosingleton ();
} else{
this._instance=new Basicsingleton ();
}
return this._instance;
};
Here, getinstance becomes a bit like the factory (factory) approach, and when we access it, we don't need to update every access point in the code. The Foosingleton (above) will be a Basicsingleton subclass and will implement the same interface.
so the question is, why delay the execution of the singleton?
In C + +, Singleton is responsible for isolating the unpredictability of the dynamic initialization order and returning control to the programmer.
Note the difference between the static instance (object) and Singleton of the class: When Singleton can be implemented as a static instance, it can also delay construction until a static instance needs to be used without using resources or memory.
If we have a static object that can be initialized directly, it is necessary to ensure that the order in which the code is executed is always the same (for example, when the Objcar needs to be objwheel during initialization), it does not scale when we have a large number of source files.
Both singleton and static objects are useful, but we should not overuse them in the same way and should not overuse other patterns. Best Practices
In practice, the singleton pattern is useful when you really need an object in the system to coordinate other objects, where you can see the use of patterns in this context:
var singletontester= (function () {
//options: Object containing singleton required configuration information
//@eg: var options={name: "Test", Pointx:5} ;
function Singleton (options) {
//If options are not provided, set to empty object
Options=options | | {};
Not singleton set some properties
this.name= "Singletontester";
this.pointx=options.pointx| | 6;
this.pointy=options.pointy| | ;
}
Instance Holder
Var instance;
Simulation of static variables and methods
var _static={
name: "Singletontester",
//Get instance method, return singleton instance
of singleton object Getinstance:function (options) {
if (instance===undefined) {
instance=new Singleton (options);
}
return instance;
}
;
return _static;
}) ();
var singletontest=singletontester.getinstance ({
pointx:5
});
Record the output of the POINTX for verification
//output: 5
console.log (SINGLETONTEST.POINTX);
Summary
Singleton is useful, and often when it is found in JavaScript, it means we may need to reassess our design. The presence of singleton tends to be that the modules in the surface system are either tightly coupled, or that their logical mandarin is scattered across multiple parts of the code base. because of a series of problems: from hidden dependencies to the difficulty of creating multiple instances, the difficulty of underlying dependencies, and so on, singleton tests are more difficult.