The singleton pattern
The singleton pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique objects directly, without instantiating the objects of the class.
let Singlton = function (name: string) {
this.name = name;
};
Singlton.prototype.getName = function () {
console.log(this.name);
};
let ProxyCreateSingleton:typeof Singlton = (function () {
let instance = null;
return function (name: string) {
if (instance) {
return instance
}
return instance = new Singlton(name);
}
})();
let bob = new ProxyCreateSingleton("bob");
console.log(bob.getName()); // "bob"
let lili = new ProxyCreateSingleton("lili");
console.log(lili.getName()); // "bob"
Copy the code
advantages
- Having only one instance in memory reduces memory overhead, especially when instances are frequently created and destroyed
- Avoid multiple occupancy of resources
disadvantages
- No interface, no inheritance.
JQuery is also a singleton, but uses the method of mounting instances into global variables, which causes global contamination.
(function () {
var jquery = (function () { })();
window.jQuery = window.$ = jQuery; ; }) (window);
Copy the code
There are many implementations of the singleton pattern, the main tenet being to allow only one instance at a time.