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. Hopefully this article was helpful for you. If so, let me know! Leave a comment or email me at marcel@codeofdoom.com
Beware, it is a nightmare to write unit tests for an application that uses Singletons to store state.
Assuming that you singleton pattern is written in Java, note that the code is not thread-safe as long as you make the getInstance() method synchronized.
The initialization of instance is verbose and not thread-safe.
How about this :
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){}
}
Or even better:
public enum Singleton {
INSTANCE;
}
(see Bloch’s Effective Java, 2nd edition).
You say that it is better not to use a static class if you need state. Why can’t you just use static variables?
@teo:
1) The instance would need to be public.
2) A small downside of this is that now Singleton is always initialized, even if it isn’t used.
@Jordi
In the newer Java compilers a Singleton instance is not initialized until it is first used.
@teo
If you try to use this(Singleton)in other class how will you get instance of it(new Singleton())?
A static method of return type instance should be present.
Thanks.
Really good one .
For a full fledged implementation clone() should also be overriden and cloneNotSupportedException should be thrown.
what will be the scenario when a singleton will not be singleton. OR What are the drawbacks of singleton ?
Thanks for posting this very helpful information; I happened to come to your blog just searching around the web. Please keep up the good work!
Do not cash to buy a car? You not have to worry, because it is possible to get the mortgage loans to work out such problems. Hence take a collateral loan to buy everything you need.
Awesome explaination. Thanks
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.
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. Hopefully this article was helpful for you. If so, let me know! Leave a comment or email me at marcel@codeofdoom.com
This is a very useful article. Thanks for posting.
Can you give me a example where you actually need to save state of singleton instance.
This is very useful article.
I am surpised you have published this version of Singleton implementation, while elsewhere in your site, you talk about menotring Junior programmers. This is exactly the kind of errors inexpereinced programmers make.
Nice Post man..keep it up
@Jordi
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
This method has a number of advantages:
The instance is not constructed until the class is used.
There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.
This method also has some drawbacks:
This is one of the most widely misunderstood patterns….
Wen u mentioned that u gonna explain it in a nutshell i frankly didn’t believe it , but u actually did it . Really good explanation , especially the diff between static and singleton .
No man you are not write.this is correct.
If you want to add some property then you must have to declare as public type.
@Jordi
This is really a very good article and it has helped me a lot in understanding the singleton classes and difference between static and singleton. Thanks.
Thanks for the tutorial, it helped me a lot, it could be better if you can more elaborately differentiate single ton with a static class. i mean to say that i need some more clarification which makes the difference in single ton with a static class… will be very useful with an example.
Thanks
Nagaraju