The Singleton Pattern
The Singleton pattern is thus known because it restricts instantiation of a class to a single object. Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the Class if one doesn ' t exist. In the event of an instance already existing, it simply returns a reference to that object.
singletons differ from static classes (or objects) as we can delay their initialization, generally because they r Equire Some information that may is not available during initialization time. They don ' t provide a-to-code that's unaware of a previous reference to them to easily retrieve them. This is because it's neither the object or "class" That's returned by a Singleton, it ' s a structure. Think of how closured variables aren ' t actually closures-the function scope This provides the closure is the closure.
In JavaScript, singletons serve as a Gkfx resource namespace which isolate implementation code from the global namespace So-provide a single point of access for functions.
We can implement a Singleton as follows:
varMysingleton = (function () { //Instance Stores a reference to the Singleton varinstance; functioninit () {//Singleton //Private methods and variables functionPrivatemethod () {Console.log ("I am Private" ); } varPrivatevariable = "Im also private"; varPrivaterandomnumber =Math.random (); return { //Public methods and variablesPublicmethod:function() {Console.log ("The public can see me!" ); }, Publicproperty:"I am also public", GetRandomNumber:function() { returnPrivaterandomnumber; } }; }; return { //Get The Singleton instance if one exists //or create one if it doesn ' tGetInstance:function () { if( !instance) {Instance=init (); } returninstance; } }; })(); varMybadsingleton = (function () { //Instance Stores a reference to the Singleton varinstance; functioninit () {//Singleton varPrivaterandomnumber =Math.random (); return{getrandomnumber:function() { returnPrivaterandomnumber; } }; }; return { //Always create a new Singleton instanceGetInstance:function() {instance=init (); returninstance; } }; })(); //Usage: varSinglea =mysingleton.getinstance ();varSingleb =mysingleton.getinstance (); Console.log (Singlea.getrandomnumber ()= = = Singleb.getrandomnumber ());//true varBadsinglea =mybadsingleton.getinstance ();varBadsingleb =mybadsingleton.getinstance (); Console.log (Badsinglea.getrandomnumber ()!== Badsingleb.getrandomnumber ());//true //Note:as We are working with random numbers, there is a//mathematical possibility both numbers would be the same,//however unlikely. The above example should otherwise still//be valid.
What makes the Singleton are the global access to the instance (generally through MySingleton.getInstance()
) as we don ' t (at least in static LA Nguages) call new MySingleton()
directly. This is however possible in JavaScript.
The GoF book, the applicability of the Singleton pattern is described as follows:
- There must be exactly one instance of a class, and it must is accessible to clients from a well-known access point.
- When the sole instance should is extensible by subclassing, and clients should is able to use an extended instance without modifying their code.
The second of these points refers to a case where we might need code such as:
mysingleton.getinstance = function () { if (this . _instance = null if (Isfoo ()) { this . _instance = new Foosingleton (); else { this . _instance = Basicsingleton (); }} return this ._instance;};
Here, the getInstance
becomes a little like a Factory method and we don't need to the update each of our code accessing it. FooSingleton
Above would be a subclass of and BasicSingleton
implement the same interface.
Why are deferring execution considered important for a Singleton?:
in C + + it serves to isolate from the unpredictability of the order of dynamic initialization, returning control to T He programmer.
It is important to note the difference between a static instance of a class (object) and a singleton:whilst a Singleton c An is implemented as a static instance, it can also be constructed lazily, without the need for resources nor memory until This is actually needed.
If we have a static object which can be initialized directly, we need to ensure the code was always executed in the same Ord ER (e.g in case objCar
needs objWheel
during it initialization) and this doesn ' t scale when you have a large number of source Files.
Both singletons and static objects is useful but they shouldn ' t is overused-the same it in which we shouldn ' t overuse Other patterns.
In practice, the Singleton pattern was useful when exactly one object was needed to coordinate others across a system. Here are one example with the pattern being used in this context:
varSingletontester = (function () { //Options:an object containing configuration options for the singleton //e.g var options = {name: "Test", pointx:5}; functionSingleton (options) {//SET options to the options supplied //or an empty object if none is providedoptions = Options | | {}; //set some properties for our singleton This. Name = "Singletontester"; This. Pointx = Options.pointx | | 6; This. Pointy = Options.pointy | | 10; } //Our instance holder varinstance; //An emulation of static variables and methods var_static ={name:"Singletontester", //Method for getting an instance. It returns //a singleton instance of a singleton objectGetInstance:function(options) {if(Instance = = =undefined) {Instance=NewSingleton (options); } returninstance; } }; return_static;}) (); varSingletontest =singletontester.getinstance ({pointx:5}); //Log the output of pointx just to verify it is correct//Outputs:5Console.log (SINGLETONTEST.POINTX);
Whilst the Singleton have valid uses, often when we find ourselves needing it in JavaScript it's a sign that we could need to Re-evaluate our design.
They ' re often an indication the modules in a system be either tightly coupled or that logic is overly spread across mult Iple parts of a codebase. Singletons can is more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating Multip Le instances, difficulty in stubbing dependencies and so on.
Miller Medeiros have previously recommended this excellent article on the Singleton and their various issues for further read ing as well as the comments-article, discussing how singletons can increase tight coupling. I ' m happy to second these recommendations as both pieces raise many important points about this pattern that is also wort H noting.
Learning JavaScript Design Patterns the Singleton Pattern