The Singleton pattern

Only one instance of a class can be generated, and the class provides a global access point for external access to the instance.

The responsibility for creating objects and managing singletons is split between two different methods that together have the power of the singleton pattern.

Using closures:

const Singleton = function(name) { this.name = name; } Single.prototype.getName = function() { alert(this.name); } Singleton.getInatance = (function(name){ let instance; return function(name) { if(! instance) { instance = new Singleton(name); } return instance; } })() var a = Singleton.getInstance('ConardLi'); var b = Singleton.getInatance('ConardLi'); console.log(a === b);Copy the code

advantages

  • Partition namespaceReduce global variables
  • Enhanced modularity,Own codeOrganized in aThe global variableName, in a single location, easy to maintain
  • And will onlyInstantiate once. Simplifies code debugging and maintenance

disadvantages

  • Because the singleton pattern provides a single point of access, it can lead to strong coupling between modules that is not conducive to unit testing.

  • You cannot test a class that calls a method from a singleton alone, but only with that singleton as a unit.

scenario

  • Define namespaces and implement branching methods
  • The login dialog
  • Store in vuex and Redux