1. Intention
Guarantees that there is only one instance of a class, and provides a global access point to it.
2. Motivation
For some classes it is important to have only one instance. For example, there should only be one file system and one resource manager in the operating system. An accounting system can only focus on one company, and a class can only have one monitor.
How do we ensure that a class has only one instance and can be accessed. Restricting the creation of new objects, we restrict access to the constructor, this step is ok, let the class itself be responsible for keeping its only instance. This class can guarantee that no other instance can be created (by intercepting the request to create a new object), and it can provide a method to access the instance, which is the Singleton pattern. But it can only be limited to object-oriented languages such as java c++, because they can use the private keyword to restrict the invocation of constructors.
accomplish:
Because there is no way to privatize the constructor, what I think is to throw new an Error object in the constructor in the reference book, and declare a getInstance method to return a class-level object (that is, the prototype, which can be understood as a static member in java for the time being ).
Write this first:
Because ts needs to use hack to extend the string type property on the prototype, the converted code is different from what I think, so I directly add the js code:
This is actually possible, but it makes no sense to write this way, because you can't instantiate a Singleton object, you can only do this
x = Singleton.prototype.getInstance()
y = Singleton.prototype.getInstance()
x === y //true
So I changed the code:
But this way the outside world can change the instance at will, we will improve the code through the practice of closure-" module pattern -module pattern :
参考:simplest-cleanest-way-to-implement-singleton-in-javascript
singleton-pattern-in-nodejs-is-it-needed
《design pattern》3.5节