Home > Best Practices, Design Patterns > How and when to use Singleton classes

How and when to use Singleton classes

April 20th, 2008

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

Best Practices, Design Patterns

  1. February 3rd, 2009 at 21:20 | #1

    Beware, it is a nightmare to write unit tests for an application that uses Singletons to store state.

  2. February 20th, 2009 at 15:00 | #2

    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.

  3. teo
    March 17th, 2009 at 03:46 | #3

    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).

  4. Jordi
    March 17th, 2009 at 18:27 | #4

    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.

  5. Anonymous
    August 17th, 2009 at 08:51 | #5

    @Jordi
    In the newer Java compilers a Singleton instance is not initialized until it is first used.

  6. Satish
    February 8th, 2010 at 10:27 | #6

    @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.

  7. arun
    February 10th, 2010 at 12:13 | #7

    Thanks.
    Really good one .

  8. February 18th, 2010 at 08:03 | #8

    For a full fledged implementation clone() should also be overriden and cloneNotSupportedException should be thrown.

  9. Anonymous
    May 22nd, 2010 at 08:47 | #9

    what will be the scenario when a singleton will not be singleton. OR What are the drawbacks of singleton ?

  10. June 15th, 2010 at 05:01 | #10

    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!

  11. July 21st, 2010 at 13:53 | #11

    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.

  12. February 5th, 2011 at 03:03 | #12

    Awesome explaination. Thanks

  13. any
    August 5th, 2011 at 03:53 | #13

    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.

  14. any
    August 5th, 2011 at 03:54 | #14

    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

  15. KS
    August 6th, 2011 at 10:20 | #15

    This is a very useful article. Thanks for posting.

  16. shiv mohan
    September 12th, 2011 at 15:22 | #16

    Can you give me a example where you actually need to save state of singleton instance.

  17. samath jain
    September 26th, 2011 at 08:14 | #17

    This is very useful article.

  18. Ajay
    February 7th, 2012 at 12:58 | #18

    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.

  19. Gk
    February 16th, 2012 at 07:57 | #19

    Nice Post man..keep it up

  20. bhaskar
    April 23rd, 2012 at 05:48 | #20

    Good Article about the basic theory of the singleton classes

  21. Neha
    May 28th, 2012 at 12:15 | #21

    Hi,

    I want to know in case of Synchronised class , which is better to use , Synchronized class or Singleton and why ??

  22. Animesh Kumar
    September 13th, 2012 at 05:48 | #22

    @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:

  23. Oh mine
    January 14th, 2013 at 18:59 | #23

    This is one of the most widely misunderstood patterns….

  24. praveen
    January 30th, 2013 at 02:20 | #24

    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 .

  25. gyan
    February 19th, 2013 at 06:10 | #25

    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

  26. Akash
    March 28th, 2013 at 00:16 | #26

    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.

  27. nagaraju
    April 1st, 2013 at 09:53 | #27

    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

  28. Anonymous
    April 22nd, 2013 at 11:24 | #28

    Superb explanation

  29. abhinav srivastava
    May 31st, 2013 at 00:04 | #29

    It is very helpful.

  30. me
    June 7th, 2013 at 10:05 | #30

    The short answer to the question in the title is `never`. At some point when using singletons you’ll realize that there was a better way to do just that (that being whatever reason you had for using singletons). They are a nightmare when it comes to (unit) testing and the only advantage they have is something you could easily handle with your IoC

  31. June 24th, 2013 at 13:30 | #31

    This piece of writing is genuinely a good one it helps new internet
    users, who are wishing for blogging.

  1. February 2nd, 2009 at 13:55 | #1