Javascript Design Patterns - 1. The Singleton

1 03 2007

This being the first part of a series of posts that I plan to write (hopefully) I will provide bits of basics as well. So on the way to implement a Singleton pattern I also briefly show how to create classes and how to have public as well as private attributes and methods.

You can skip the basics by clicking here.

A Singleton is a class so lets start by creating one! Classes don’t exist in Javascript although the keyword class is reserved. But they can be represented by functions which will be used as the constructor you know from other OOP languages.

var myClass = function() { /* more to come here */ }

You can instantiate objects of this class by typing:

var myObject = new myClass();

Now we want to add an attribute and a method to it:

var myClass = function() { this.name = "a Simple Class Instance"; this.whatsYourName = function() { alert('Hello, I am '+this.name); } };

Try it by typing:

var myObject = new myClass(); myObject.whatsYourName();

It will alert what you expect. Now you will have noticed that the method we’ve just added as well as the attribute are both publically accessible. To add private attributes and methods I first recommend a small syntactical correction:

var myClass = function() { return { /* here starts the public 'body' */ name:"a Simple Class Instance", whatsYourName:function() { alert('Hello, I am '+this.name); } } };

What’s the difference? Well our function now returns an object. Members of which are our attribute and method. I prefer this notation to others because it visibly separates the public and the (excuse me) private parts.

Speaking of which. Javascript does not know about public and even less about private. To Javascript everything is public but it does know about closures and those we can use to add private members to our class.

Basically a closure is the body of a function. It keeps all local variables declared in it and after it is executed all its local variables get garbage-collected. Well unless.. unless there is still a reference to them. Lets do it step by step.

var myClass = function() { /* here starts the private 'body' / var birthtime = new Date(); return { / here starts the public ‘body’ */ name:”a Simple Class Instance”, whatsYourName:function() { alert(’Hello, I am ‘+this.name); } } };

So we added a local variable and after the constructor of our class returns it gets wiped from memory. Then just create a reference to it.

var myClass = function() { /* here starts the private 'body' / var birthtime = new Date(); return { / here starts the public ‘body’ */ name:”a Simple Class Instance”, whatsYourName:function() { alert(’Hello, I am ‘+this.name); alert(’I was born on ‘+birthtime.toLocaleString()); } } };

As you can see we now use the local variable birthtime in the public method whatsYourName(). This usage is called a reference and it causes the garbage collector to fail cleaning birthtime off the memory stack. So birthtime now is effectively a private variable (I’d like to call them secret though.. ). You can do the same with methods, just declare the local variable to be a function with a body to it and there you have it.

Lets carry on with the original plan to create a Singleton. What is a Singleton and when to use it? A Singleton is a Creational pattern. You can find out more here. It comes down to this: A Singleton is a class that allows you to have just one single instance. Why should you choose it over a static class then you might ask? Well a static class needs to be preconfigured to a certain task somehow whereas the initialisation of a Singleton object is dynamical. You can configure it on the first instantiation. I frequently use it for tasks that require an object that has to be configured once and be used everywhere else in the code. On the server side a good example would be a database abstraction. You configure the server, database and access once and use the object almost everywhere and you can use the same class in other scripts to connect to a different database without changing the class code itself.

Classic Singletons hold a static reference to the one and only instance, they have a private constructor to permit instantiation and they provide a public static method often named getInstance() which returns the referenced instance creating it on the first use by calling the constructor.

In Javascript all this is not necessary since it does not know about class members (there is no static keyword). We learned (or already knew) that objects are the return of a function call (such as new Object();). And you saw that the variable myClass is the reference to an otherwise anonymous function. So we have stored a function in a variable. Now we don’t need the class/function anymore than once. We want to execute it only once to get the instance and then we do not want to create another instance ever again. So why hold a reference to it? Why not execute it on the fly by simply adding the new keyword to the call:

var myClass = new function(){/* function body in here */};

or (as I prefer to do) by adding two brackets to the function declaration:

var myClass = function(){/* function body in here */}();

The variable myClass now is holds the return value of the anonymous function it previously referenced. It is thus the only instance since the function body in run time is no longer available. Therefor we should rename it to mySingleton.

Lets see a complete implementation of the above.

var mySingleton = function() { /* private attributes / var _created = new Date(); / private methods / var _calculateAge = function() { return new Date().getTime() - _created.getTime(); } return { / public attributes / name:’M.Y. Singleton’, / public methods */ tellBirthday:function() { alert(’Hello, my name is ‘+this.name+’ and I was created on ‘+_created.toLocaleString()+’.'); }, tellAge:function() { alert(’I am ‘+_calculateAge()+’ms old.’); } } }();

As a convention I’d like to precede the name of any private member with an underscore. This helps a great deal to distinguish between private members and local variables. It has no functional relevance however. I first saw this convention used in the Python language to bypass the lack of private members.

alert(mySingleton.name);

Will alert “M.Y. Singleton“.

mySingleton.tellBirthday();

This will alert “Hello, my name is M.Y. Singleton and I was created on Wednesday, 21. February 2007, 09:13:26 .” as expected.

Please note that public variables have to be accessed using the this keyword! Just like this.name when called from within a public method.

However a private method can not use the this keyword and has to use the objects name for referencing! Like mySingleton.name.

mySingleton.tellAge();

Also this will alert as expected: “I am 23456ms old.“.

alert(mySingleton._created);

As you probably guessed this will fail since we try to access a private attribute here.

alert(mySingleton._calculateAge());

Private methods can not be accessed from the outside as well so this will also fail.

Prototype style

If you are (like me) a user of the prototype library then you might want to stick to the prototype coding style.

var singleton = Class.create(); Object.extend(singleton.prototype, { initialize:function(){/* empty */}, name:'barfoo', tell:function(){alert(this.name);} }); singleton = new singleton(); singleton.tell();

Line 6 does the trick. You store the instance of a function in its reference thus overwriting the function body making it impossible to instantiate another time.

Cloning the object will still work of coursebut that’s cheating! ;)

So there you have it.

/christian

, , , , , , , , ,

Actions

Informations

10 responses to “Javascript Design Patterns - 1. The Singleton”

13 03 2007
tigerkin (10:50:12) :

Very sophistic, but I think that it’s not a correct approach to development JavaScript.

The readability and simplification is very important for coding JavaScript.

In the next version of JavaScript i.e. 2.0, the class and static, and so on keywords will be included. At that time, JavaScript will be more powerful and gentler.

Thank you for your introduction.

15 03 2007
admin (18:11:58) :

@tigerkin thank you for your comment. I agree to a certain extend. Of course readability is important not only in Javascript but the way coding Javascript works today this is just a form of notation one can get used to. As for the upcoming version of Javascript: no everybody is happy about it since the announced changes will give a whole new feel to coding JS. Ask flash developers how they like their new toy action script 4 which implements already what is future talk for Javascript. I reckon it takes away the elite feeling of the community.. well.. ;)

25 04 2007
David Foley (20:47:09) :

Christian - not a critique per se, but isn’t a Singleton a Singleton by merit of not requiring explicit instantiation (i.e. new Singleton() outside of the ‘class’ definition ) ? I looked into the area and came up this a few months ago. Its short and sweet and doesnt extend native objects

function provideSingleton ( oSuper ) {
var _private {_instance: null;}
return {
getInstance: function () {
if ( _private._instance == null ) _private._instance = new oSuper ();
return _private._instance;
}
};

To use it, just provide a JavaScript class definition to the function, and call it with the getInstance method, like this:

// rough and ready class def
function MyClass () {};
MyClass.prototype.instanceProperty = “instanceProperty”;
MyClass.prototype.instanceMethod = function () {
return this.instanceProperty;
};

var SingletonMyClass = provideSingleton ( MyClass );

var SingletonReference = SingeltonMyClass.getInstance();

SingletonMyClass.getInstance().instanceMethod() // returns ‘instance property’

SingeltonReference.instanceMethod() // returns ‘instance property’

31 08 2007
Darren Hurley (15:43:46) :

@David, I’m not sure that would work.

Firstly, what’s stopping someone creating another MyClass object by just calling new MyClass() as many times as they want?

Also, if I understand this right, the provideSingleton function returns an object which references the variable _private._instance in the containing function. But after the first time you call getInstance, this _private._instance var will be updated, never again equal to null, i.e. you can only call getInstance once.
I think the point your missing is there is only one variable _private.

(on another note, the way your initailizing this variable’s a bit wrong. This would be better
var _private = {};
_private._instance = null

)

You’re right about being able to create singleton’s dynamically, but i don’t think that’s possible in JavaScript

24 11 2007
David Foley (00:03:57) :

Hi Darren - didnt spot my post being published till now (talk about tardiness!) - actually its possible - rereading my post I realised my typos - this the correct version:

function provideSingleton (oSuper)
{
return (function()
{
var _instance = null;
return {
getInstance: function()
{
if(_instance == null) _instance = new oSuper();
return _instance;
}
};
})();
}

4 03 2008
Al (23:14:38) :

Thanks! Exactly what I’m looking for! Nice example. I too dread Javascript 2.0 even though it provides more OO features. The toolkit I use to develop JS utilizes similar coding style to yours and I’ve grown use to it.

2 04 2008
Ext Javascript Library for beginners, ext-perience Ext » Blog Archive » Javascript Singleton Pattern explained (04:14:17) :

[…] a great site with an explanation of the Singleton design pattern in Javascript with […]

24 05 2008
fatbrain (13:55:14) :

The simplest way, and most accurate is this (imo):

Consider:

var singelton = (function() { function MyObj(…) { … }; …; var o = new MyObj(…); o.constructor = null; return o; })();

It will also inhibit the user from creating more instances from new some_object.constructor(…)

1 02 2010
Samuel Cochran (07:46:35) :

Javascript has no classes (it is a prototypical language) so you don’t create singletons. Achieve the same effect by creating an object with properties and methods:

var Singleton = {
one: 1,
two: function() {
return this.one + 1;
}
};

alert(Singleton.one);
alert(Singleton.two());

2 03 2010
_private - StartTags.com (23:28:47) :

[…] not be published) (required) Website. Copyright © 2004-09 Dagon Design - WordPress Powered …prototyp.ical.ly Javascript Design Patterns - 1. The SingletonThis being the first part of a series of posts that I plan to write (hopefully) I will provide bits […]

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>