InsertAfter's Logo

Revisiting The JavaScript Singleton Pattern

Retrospective note:

⚠ Beware: This article is outdated. I now think that inherence is often not a good pattern, I'm rarely using POO in JavaScript currently too. I prefer functions composition and singleton factories that I combine thanks to dependency injection and inversion of control with Knifecycle.

JavaScript design patterns are quite good examples to sharpen your JavaScript skills. Let's take a look at the singleton pattern.

I'm currently reading Addy Osmani’s book about JavaScript design patterns. It's a very interesting introduction and I strongly recommend you this read. Viewing his Singleton Pattern implementation I had two simple ideas of improvement to get them more powerful. Here is a basic implementation of this pattern:

To the Addy's implementation I just added a fake constructor in order to prevent misuses of the singleton pattern. As you can see, the Singleton pattern purpose is to ensure there will always be only one instance of it's "class".

After reading it I wondered if there could be a way to make singletons inherence possible. I finally got it by adding a simple snippet to the previous implementation:

As you can see our singleton inherits from the parent constructor we have given it. It also can take a conventional objet constructor or another singleton.

The main use case for it is the ability to extend to another conventional constructor the singleton pattern. It also provide a way to extend existing singletons and change their behavior with no risk to alter them.

Published at jeudi 30 mai 2013 à 09:38:19.