Monday, June 4, 2012

How and when to use Singleton classes

It’s a pretty well known pattern, but I want to discuss what a Singleton class is first. In a nutshell, a Singleton class is a class that will only have one instance of the class. In certain cases, we want to make sure that we cannot instantiate multiple copies of the object, so we limit it to just one copy. Instead of having a public constructor for our class, we use a private constructor. Then we use a public method (usually named getInstance()) to make sure there is only one copy.


Here is how it looks:
1
2
3
4
5
6
7
8
9
10
11
public class Singleton {
   private static final Singleton instance;   
 
   private Singleton(){}
 
   public static Singleton getInstance() {
     if (instance == null)
       instance = new Singleton();
     return instance;
   }
 }
 
As you can see, the constructor is private, so we are unable instantiate it in the normal fashion. What you have to do is call it like this:
1
public Singleton singleton = Singleton.getInstance();
When you do this, the getInstance() method then checks to see if the parameter ‘instance’ is null. If it is, it will create a new one by calling the private constructor. After that, it just returns it. Of course, if it is not null, it just returns the existing instance of it. This insures that there is only one copy of the object within your program.

Of course, this post wouldn’t have much meat to it if thats what I left it at. So lets talk about some of the uses of a Singleton class. Also you might at some point as ‘why not just make it static?’, which is a common question, so I will go over that about that as well.

First, what are the uses of a Singleton?. Singleton classes are normally used for things such as a Factory classes, Builder classes and things like that. A few real world examples include the the SessionFactory class in Hibernate – it’s actually a singleton. Or with log4j, when you call its logger, it uses a singleton class to return it. If anyone has used Cairngorm within Flex/Actionscript 3, its model locator is a Singleton.

So why do we want to use singleton’s in these instances? Lets look at the ModelLocator example within Cairngorm. The model locator is used within Cairngorm to keep the state of data within our Flex application. But the reason why its kept in this one object is that it is used across multiple components. The data in one component is usually important to another component, so everything is managed in one central object. It’s quick to realize why we only want one of these in our program. If not, it would be pretty tough to maintain state if other components are affecting data providers that others are using.

Another question that usually comes up when it comes to using a Singleton is “Why not just use a static class?”. Static classes still have many uses and lots of times, people get confused and will use a Singleton as much as possible. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.

So here is a quick list of uses for static classes:
Math.pow(double a, double b);
Interger.parseInt(String s);
Interger.toString(int i);

As you can see, the state of these methods don’t matter. You just want to use them to perform a simple task for you. But if you coding your application and you are using a central object where state does matter(such as the ModelLocator example), then its best to use a Singleton.

The next reason you may want to use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, you probably only one of those objects floating around. This is the case for things like a if you have a factory method that is particularly robust, you want to make sure that its not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening.

The Singleton is a simple and powerful design pattern. Newer programmers may not realize what potential it has and will over look it. Others may love it so much and end of overusing it in the wrong way.

No comments:

Post a Comment