This discussion is archived
4 Replies Latest reply: Jun 13, 2013 1:06 AM by gimbal2 RSS

What is the need for singleton class ?

Pradeep Newbie
Currently Being Moderated

If i am correct, a singleton class is the one for which only one object is allowed to create right. so why can't i just use everything in that as static and access them using the class name ? what is the need to create a single object ?

  • 1. Re: What is the need for singleton class ?
    PhHein Guru Moderator
    Currently Being Moderated

    Your thread titloe produces quite a few articles like this one: http://codeofdoom.com/wordpress/2008/04/20/how-and-when-to-use-singleton-classes/

  • 2. Re: What is the need for singleton class ?
    gimbal2 Guru
    Currently Being Moderated

    Pradeep wrote:

     

    If i am correct, a singleton class is the one for which only one object is allowed to create right. so why can't i just use everything in that as static and access them using the class name ? what is the need to create a single object ?

    Well the benefit of having an actual instance is that you can still use object properties to keep state. On top of that it is far easier to wrap/hook/mock such classes, for example for unit testing purposes.

  • 3. Re: What is the need for singleton class ?
    jwenting Journeyer
    Currently Being Moderated

    to play devil's advocate, you could store state in static members.

     

    Far more important is that it's a lot easier to turn something into a singleton and back into an object that can have multiple instances than it is to move something from being a mess of static members to being an instantiable class and back.

    Of course there will be potholes and gotchas still, as there no doubt was a reason for that thing to be a singleton that need to be addressed.

     

    And then there's the good old "the only good global is a deleted global" that speaks against statics in general (though in a way also against singletons I guess).

     

    Of course singletons aren't really, they're unique only within the context of their classloader.

  • 4. Re: What is the need for singleton class ?
    gimbal2 Guru
    Currently Being Moderated

    jwenting wrote:

     

    to play devil's advocate, you could store state in static members.

     

    Ugh People new to the language tend to want to stick everything in statics to not have to deal with learning how to work with objects, I try to avoid mentioning it is possible