What are the scenarios when Singleton design pattern is preferred over static class & when static class is preferred over Singleton design pattern?
This is not really an either or scenario.
Singletons are instances with a static getter, and a private constructor. They are not static classes.
Singleton with certain provisos is a way of ensuring you only have one instance of class.
So the first question is. Do you need an instance, i.e. does this thing have a state, the second question is given how difficult they make unit testing, do you want one at all.
Have a look at the Service Locator pattern, for instance.
Generally singletons are superior to static classes.
Singleton in contrary to static class:
If you choose static class then you choose concrete, there's no flexibility. However, if you use singleton you have to remember to make the instantiation of it thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With