22 March 2013
The singleton is a practical design pattern, that’s the reason it is so popular amongst beginners. It is also an anti-pattern because of the problems it introduces (global state, difficult to test, …).
While I agree with that, and the fact that Singletons should be used with (a lot of) moderation, I also like an alternative pattern which comes with the advantage of the singleton and balances out its disadvantages. This can be useful if you have to work on a codebase that has singletons.
I’m calling this pattern the Optional Singleton for lack of a better name.
Simply put, this is a class which you can use as a singleton, or not (it’s optional ;):
- you can still use the handy
- you can however create new instances of the class, for example for tests