I have spent the last couple of hours reading about the singleton pattern and why not to use it, amongst others those really good sites:
- Singleton I love you, but you're bringing me down
- How to Think About the "new" Operator with Respect to Unit Testing
- Where have all the Singletons Gone?
I guess quite a lot of you know these already.
Looking at my code after reading that, I clearly am one of the maybe 95% of programmers that misunderstood and misused the singleton pattern.
For some cases, I can clearly remove the pattern, but there are cases where I am unsure what to do:
I know singletons for logging are accepted, one reason for that being that information only flows into them but not back into the application (just into the log file or console etc of course).
What about other classes which do not meet that criteria but are required by a lot of classes?
For example, I have a settings object which is required by a lot of classes. By a lot, I mean more than 200.
I have read into some other SO questions like "Singletons: good design or a crutch?", and all of them pointed out why using singletons is discouraged.
I understand the reasons for that, but I still have one major question:
How do I design a class which needs a single instance, accessible from everywhere, if not using the Singleton pattern?
The options I can think of would be:
- Use a static class instead (though I don't see how this would be any better, looking at OOP and unit testing).
- Have it created in an ApplicationFactory and perform dependency injection on every single class that needs it (keep in mind it's 200+ for some cases).
- Use a singleton anyway, as the global access bonus outweighs the disadvantages for that case.
- Something completely different.