What’s wrong with singleton?
Singletons: good design or a crutch?
Singleton: How should it be used
What is so bad about Singletons
You can find numerous reasons for using a Singleton over a Static class. But there must surely be some situations where it is better to use a static class before a Singleton. What are they?
It is not possible to inherit from a static class, while it is possible with singleton pattern if you want to allow it. So, anyone can inherit from a singleton class, override a method and replace the service. It is not possible to write an extension method to a static class while it is possible for a singleton object.
The difference between the Singleton and Static is Singleton Class can have value when Class object instantiated between server and client, such a way if three client want to have a shared data between them Singleton can be used. Static are always just shared and have no instance but multiple references.
Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.
Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.
You can use static class when:
1) all its methods are utilities (nice example - class Math)
2) you don't want to deal with preserving your instance from garbage collector (in applets), but I would better use singleton there
3) you are absolutely sure that it wouldn't become stateful in the future and you are sure that you will always need only one instance of that class
If you are using singleton and in one moment you realize that you need several instances then your singleton easily can be transformed to multitone, but you'll have a problem with static class
Having fought with the testability of consumers of static classes over the years I can honestly say that they are the work of evil minds. Seriously though, I'd use static classes for extention methods in C# but not really anywhere else.
If your class doesn't store any state, then use a Static class.
If it stores state and you require a single instance, then (maybe) use a Singleton.
Otherwise use a regular class.
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