What are the real world applications of the singleton pattern?


Question

Duplicate

On design patterns: When should I use the singleton?

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
                instance = new Singleton();

            return instance;
        }
    }
}
1
15
2/25/2018 2:06:29 PM

Simple. What does a singleton do?

  • It provides global access to an instance of an object, and
  • It guarantees that no more than one instance of that type can ever be created.

So you use a singleton when you need both of these things.

And that is rare. Globals are generally speaking, bad. We tend to avoid them when possible. And building your application around the assumption that "if more than one instance exists, it is an error" is dangerous, because you typically find out the assumption didn't hold. Perhaps you want to be able to create multiple instances locally, for caching purposes. Perhaps it turns out you need more than one database, more than one log, or perhaps threading performance requires you to give each thread its own instance.

In any case, you don't need to enforce the "only one instance may exist" assumption. If you only need one instance, simply create only one instance. But leave the constructor publicly visible so that more instances can be created if it turns out to be necessary.

In other words, both of the features offered by a singleton are actually negatives. In general, we don't want our data to be globally visible, and we don't want to take away flexibility for no reason.

If you do need one of the features offered by a singleton, implement that one feature, without the other. If you need something to be globally accessible, make it a global. Not a singleton. And if you do need to enforce that only one instance will exist (I can't think of any plausible situations where you'd want this), then implement that, without the global visibility.

The only real world application of singletons I've ever seen has been "an architect has read the GoF book, and decided to cram design patterns in everywhere.", or "some programmer stuck in the 80's isn't comfortable with the whole "object oriented" thing, and wants to code procedurally, which means storing data as globals. And singletons sounds like an "OOP" way to make globals without getting yelled at".

The key point is that a singleton mixes two, very different, and each very rarely needed, responsibilities. Typically, you want at most one of those in any given object.

16
8/13/2014 7:20:04 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon