Quantcast
Viewing all articles
Browse latest Browse all 11

Answer by tdammers for Alternatives to the singleton pattern

The purpose of a singleton is to enforce that only one instance can ever exists within a certain realm. This means that a singleton is useful if you have strong reasons to enforce singleton behavior; in practice, this is seldom the case though, and multi-processing and multi-threading certainly blur the meaning of 'unique' - is it one instance per machine, per process, per thread, per request? And does your singleton implementation take care of race conditions?

Instead of singleton, I prefer using either of:

  • short-lived local instances, e.g. for a factory: typical factory classes have minimal amounts of state, if any, and there is no real reason to keep them alive after they have served their purpose; the overhead of creating and deleting classes is nothing to worry about in 99% of all real-world scenarios
  • passing an instance around, e.g. for a resource manager: these have to be long-lived, because loading resources is expensive and you want to keep them in memory, but there is absolutely no reason to prevent further instances from being created - who knows, maybe it will make sense to have a second resource manager a few months down the road...

The reason being that a singleton is global state in disguise, which means it introduces a high degree of coupling throughout the application - any part of your code can grab the singleton instance from anywhere with minimal effort. If you use local objects or pass instances around, you have a lot more control, and you can keep your scopes small and your dependencies narrow.


Viewing all articles
Browse latest Browse all 11

Trending Articles