What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
The true answer is by Jon Skeet, on another forum here.
interface
with a Singleton class, but a class's static methods (or e.g. a C#static class
) cannot.The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.
Quick Example:
To illustrate Jon's point what's shown below cannot be done if Logger was a static class.The class
SomeClass
expects an instance ofILogger
implementation to be passed into its constructor.Singleton class is important for dependency injection to be possible.
a. Serialization - Static members belong to the class and hence can't be serialized.
b. Though we have made the constructor private, static member variables still will be carried to subclass.
c. We can't do lazy initialization as everything will be loaded upon class loading only.