I've written it before, but it's not very thorough---to do it again.
Single-Case mode:
Definition: Guarantees that a class has only one instance and provides a global access point to access it.
Application Scenarios:
If a pair of images needs to be created only once, a singleton pattern is required, such as thread pool, global cache, widow object in the browser, and so on.
Realize:
Use a variable to record whether an object has already been created for a class, and if so, the next time the class instance is fetched. Directly returns the object that was created before.
//single-case modevarSingleton =function(name) { This. Name =name; This. Instance =NULL;};//Get Instance Objectfunctiongetinstance (name) {if(! This. Instance) {//once instantiated, it is not instantiated This. Instance =NewSingleton (name); } return This. instance;}//example of testing a singleton patternvarA = getinstance ("AA"); --->AAvarb = getinstance ("BB"); --->AA
Console.log (A = = b)//true
You will find that the logic of creating instances and the logic of managing the Singleton are put together; this does not conform to the principle of "single duty"
We have improved the use of the proxy in the way of using singleton mode
varSingleton =function(name) { This. Name =name;};varGetsingleton = (function() { varinstance; return function(name) {if(!instance) {Instance=NewSingleton (name); } returninstance; }})();varA =NewGetsingleton (' AA ');varb =NewGetsingleton (' BB ')); Console.log (a= = = B)//true
Although the separation is done, you will find that the public part of the code still exists.
And so it was improved to
varSingleton =function(name) { This. Name =name;};varGetsingle =function(FN) {varresult; return function() {returnResult | | (result = fn. Apply ( This, arguments)); }};varCreatesingle =Getsingle (Singleton)varA = Createsingle (' AA '))varb = createsingle (' BB ')) Console.log (a= = b)
Well, if you just write that to the point, it's basically the same.
JS design mode (i)---single case mode