The singleton pattern is defined to ensure that a class has only one instance and provide a global access point to access it.

Based on the singleton

I wrote a simple example, this example is very simple, using the inert function property.

On the first request, you override all of your methods so that on the first get request, you override all of your methods.

We’ll create a new getInstance and reset the prototype chain for this. This will never create a new getInstance in the future.

var getInstance = function (value){
    this.value = value;
}
getInstance.prototype.getValue = function () {
    return this.value;
}
getInstance.prototype.get = function (value) {
    this.value = value;
    return this;
}

getInstance.get = function(value){
    Object.assign(this.new getInstance(value))
    return this;
}
var a = getInstance.get('a')
var b = getInstance.get('b')
console.log(a===b);

>> true
Copy the code

Transparent singleton

Transparent singletons mean that the user still generates a class as normal new, but the same class is returned to the user no matter how many times the class is new.

var CreateInstance = (function(){
    var instance;
    var CreateFn = function(value){
        if(instance){
            return instance;
        }        
        return instance = this;

    }
    return CreateFn
})()
var a = new CreateInstance('a')
var b = new CreateInstance('b')
console.log(a===b);

>> true
Copy the code

A transparent singleton is created with a unique instance already in place, and the same instance is used all the time

Implement the singleton pattern with a proxy

The proxy mode is the extraction of the real entity method of creation, preserving the creation process. The proxy class is only responsible for managing singleton objects.

var ProxyInstance = (function(){
    var instance;
    return function(value){
        if(! instance){ instance =new CreateInstance(value);
        }        
        return instance;
    }
})()

var a = new CreateInstance('a')
var b = new CreateInstance('b')
console.log(a===b);

>> true
Copy the code

summary

Singletons are a simple pattern, and understanding singletons will help you understand the concepts of closures and higher-order functions.

Link: blog.yodfz.com/frontEnd/20…