Singleton Design Pattern

by Trevor Page on January 5, 2013

Singleton Design PatternI remember back in my days at university, sitting in lecture while a professor droned on about important concepts in programming. The topic at hand was design patterns, and this terminology meant absolutely nothing to me. Perhaps the professor had explained the importance of the subject and I had glazed over it, but nevertheless I was only half listening while I thought of all the other things I could have been doing at that moment.

So I’ll make it my mission to ensure that the same fate does not fall upon you, my faithful reader. Pay attention, because this is one of many topics that are very important as you make your way to becoming a professional programmer.

What the heck is a Design Pattern?

Well, in programming there’s been a history of really bad applications and really good applications. So what separates the bad from the good? Well it’s all about identifying common scenarios that come up in code, and being able to provide the tried-and-true BEST solution for any given coding scenario. That’s what design patterns are all about. They are essentially a collection of well defined rules that help you to decide how your code should function when dealing with common coding problems. These design patterns have come from the good, the bad and the ugly code of programmers’ past… you’re familiar with the term “learn from your mistakes”? That’s what design patterns are all about.

So, you see why I asked you to pay attention? Creating code based on other people’s knowledge is a great way to come out ahead, because why would you want to go through the pain of implementing a solution that’s full of design flaws, feel the pain of those flaws, then have to fix them (usually in a time-constrained environment with customers screaming). Nobody likes that, so let’s plan ahead shall we?

Enter the Singleton Design Pattern

The singleton design pattern is one of many design patterns, but the singleton is one of the most used and well known. Let’s see what Wiki has to say about it:

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

Not bad, a decent definition. If I were to put it in terms of the Highlander film, I would say “There can be only one!” So this means that literally only one instantiation of an Object will be allowed, you simply should not be able to have two separate instances in your application. Okay, fair enough, seems like a simple enough concept but, how is that useful to us?

Well the most popular use of the singleton design pattern are for Objects that deal with things like database connections or controllers in the MVC pattern. I haven’t really talked much about databases or MVC, but the reason these things use the singleton design pattern is because it would be a waste of system resources to create more than one instance of those Objects. When you’re dealing with an Object that talks to a database, it’s fairly “expensive” to create a connection to a database. When the object gets created, one of the first things it will do is create a connection to the database, but once the connection is open you can use it over and over again. So since there’s this “cost” of creating the Object, wouldn’t it be nice if we had some way of ensuring we would only create it once? Well yes it would be nice, so let’s make it a singleton!

Show me an example!

Okay, let’s take a look at what a singleton would look like in Java:

public class SingletonObject
{
    private static SingletonObject INSTANCE;

    private SingletonObject()
    {
    }

    public static SingletonObject getInstance()
    {
      if (INSTANCE == null)
          INSTANCE = new SingletonObject();
      return INSTANCE;
    }
}

So, there are a few important elements to this code. The first element is that we have declared the constructor as private. If this is your first time seeing a singleton, you likely glazed over that fact (I know I did the first time seeing it). But this is a very important piece of code. The fact that we’re making the constructor private, means that we don’t want any other code being able to access the constructor… this means of course, that no one will be able to instantiate this Object (they would get a compilation error). That is after-all, our goal here, to only ever have at most one instance. So when you take away access to the constructor, you take away the ability for a random rogue coder to accidentally instantiate the object.

The second important thing to note is that we have a static reference to an INSTANCE variable. This is how we will be able to actually work with the Object. If you think about it, how else would you use an Object that you’re not allowed to instantiate? So if I can’t write the following:

SingletonObject myObject = new SingletonObject();

then how can I use this stupid Object!? Well, when you have a static INSTANCE variable and a static getter for that INSTANCE, you can access it like this:

SingletonObject.getInstance();

So what will happen now is the following:

  1. If this is the first time the getInstance method has been called, then the INSTANCE variable will be null, and the SingletonObject will instantiate a new version of itself (it can do this because it and only it is allowed to access it’s own private constructor)
  2. If this is not the first time the getInstance method has been called, then the code will NOT instantiate a new Object, it will simply return the existing one

And voila! We now have an Object that will only ever have at most one of itself in existence. Not too shabby eh? Oh, by the way, make sure you understand this concept as well, because you will be tested to reproduce a singleton in the next practice assignment ;)

Okay ladies and gentlemen, that’s enough learning for today. Now that the hard part is over, why don’t you take a moment to share this article with your friends on your favourite social network? Please click on one of the social media sharing buttons in the top left corner of your screen… seriously… you’re reading this right now, and I know you have an social media account! So go tweet it, or like it, or stumble it, whatever you like… just get the word out already! More people need to see this stuff, and you have the secret to making that happen. It’ll make you feel all warm and tingly inside if you share, I promise! :)

{ 1 comment… read it below or add one }

Leave a Comment

Powered by sweet Captcha

{ 1 trackback }

Previous post:

Next post: