Is the singleton design pattern inherently flawed? I don’t think so.
Can you abuse the singleton pattern? Certainly. Can you use it effectively? Absolutely.
A few questions I ask myself when deciding whether singletons really should be singletons:
- Is the singleton external to my app? Databases, queuing services, and ESBs are all perfectly valid macro examples of the singleton pattern.
- KISS: Is my entire app limited to 2-3 internal singletons?
- DRY: Are my singletons inherently global? In other words, if they weren’t singletons, would I have to plumb references to them into almost every object? (e.g., a logger or mediator)?
- Do my singletons depend only on each other, and/or the operating environment?
- Have I ensured proper start-up and shut-down sequences for each singleton, including memory management considerations? For example, a “Grand Central”-style thread pool may require Run() and Shutdown() methods. These methods would be invoked during app startup and shutdown, so that tasks are guaranteed to run only when the objects they operate on are in a valid state.
I can’t hear ahynting over the sound of how awesome this article is.