The singleton pattern

Ensure that there is only one instance of a class and provide an access point.

Implement the singleton pattern

Create a class to get the object with getInstance

var Singleton = function (name) {
  this.name = name
}
Singleton.prototype.getName = function() {alert(this.name)} // Bind Singleton to class singleton.getInstance =function(name) {
  if(! this.instance){ this.instance = new Singleton(name) }return} // create singleton.getInstance = (function(){
  var instance = null
  return function(name) {
    if(! this.instance){ this.instance = new Singleton(name) }return this.instance
  }
})()
```var Singleton= (function() {
  var instance
  return function(name){
    if(instance) {
      return instance
    }
    this.name = name
    return instance=this
   }
 })()
Copy the code

One drawback, however, is that Java implements singletons by privatizing constructors, whereas in the example above you can still get the instance through New Singleton().

To improve the

var Singleton= (function() {
  var instance
  return function Single(name){
    if(instance) {
      return instance
    }
    this.name = name
    return instance=this
   }
 })()
Copy the code

Objects are created by anonymous functions, but this Single is a bit odd, not exactly a class (with a return value), just a function.

The proxy implements singletons

function Singleton(name){
    if(instance) {
      return instance
    }
    this.name = name
    return instance=this
 }

var ProxySingleton = (function() {
  var instance
  return function (name){
    if(! instance) { instance = new Singleton(name) }return instance
   }
 })()
Copy the code

Singletons are implemented through the proxy, and the Singleton itself does not change, just fetching objects through the proxy.

conclusion

To be precise, the singleton pattern only exists in Java, because Java is class-based and all objects are instances of classes, whereas in JavaScript everything is an object. Global objects can also be considered singletons, and implementing singletons is just an imitation.