Defined
The singleton pattern is that a class can only instantiate an object and provides a global access point to access it.
Generally in the implementation of the login box, or a global controller will use the singleton mode. In reality, there are window objects, thread pools, global caches, and so on.
Simple implementation
var function (name) { this. Name = name; This NULL function(name) { if(! this. Instance) { thisnew person (name); } return This . instance;}
Kinds
The implementation of the singleton pattern is made up of many ways, and they also have different effects.
1. A single example implemented with a proxy
Sometimes, a proxy is used if you want a class to create an instance from a proxy, and you can use the normal method new for many instances.
var person = function this . Name = name;}; var Createperson = (function () { var instance; return function if (! return new person (name); return instance; }});
In the above code, if we were to create an instance, we would use Createperson to create it, and if it was like a normal object, it would be created with new.
2. Inertia single case
In fact, the simple singleton pattern introduced is the lazy Singleton, that is, the instance is created when needed. Instead of creating it from the beginning.
Design Patterns in javascript: Singleton mode