Design Patterns a Deep Dive Into…

Singleton, Part 1

Recently I had a senior developer point out the gaps in my knowledge in Computer Science and Javascript. One of the questions he asked me if I knew what were Design Patterns. I stopped like a deer in headlights wondering what he meant, I couldn’t even really come up with an educated guess so he told me to look into Singleton, Builder, Factory, and Observer. Let’s start with Singleton.

Well actually before we start let’s explain what are design patterns.

Design Patterns are documented solution to commonly occurring problems in software engineering. Engineers don’t have to bang their heads on the problems that someone else has already solved. — Ankita Masand, a JavaScript Enthusiast

Design Patterns can be broken apart into 3 categories Creational, Structural, and Behavioral. Creational is for handling Object creation mechanisms. Structural is for identifying ways to realize relationships between objects. Finally Behavioral is for handling communication between different objects.

Singleton falls under the creational pattern and provides the best way to create an object, though it has some pitfalls. This helps create an object that is easy to implement, change, test and reuse. It solves problems such as,

  1. How can it be ensured that a class has only one instance?

Singleton hides the constructor of the class and defines a public static operation that returns the sole instance of the class. This can solve problems such an instance of a User’s Session, config settings for a web app, or reducing multiple analytics in a client-side web application. It would look something like this:

However, let’s say this is your first time making this. Well maybe you need a better example then some generic code someone wrote. Maybe you need a real world example. Well let’s think about our Planet, Earth. It was initiated a long time ago and now we all have access to the resources, attributes, and functionality. We can all access the Earth and its methods but we cannot create another one. Whatever we do to this planet is done and we can all access that information but that’s it. So the code for initiating Earth could look something like….

Because of this forced limitation, Singleton breaks object-oriented design principles since it cannot be inherited from, we have no control over the creation, and it prevents dependency inject. It also does not allow for any test-driven development either since there can’t be a clean instance of a the object and mock objects cannot properly be used in tests.

Overall the usage of Singleton is powerful, but definitely for specific moments when implementing the design. It is used when you do not want to allow for a user to create more instances of sensitive or large sets of data.