Difference between static class and singleton pattern?

Viewed 609085

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?

41 Answers

What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.

The true answer is by Jon Skeet, on another forum here.

A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

A static class allows only static methods.

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.

static classes are not for anything that needs state. It is useful for putting a bunch of functions together i.e Math (or Utils in projects). So the class name just gives us a clue where we can find the functions and nothing more.

Singleton is my favorite pattern and I use it to manage something at a single point. It's more flexible than static classes and can maintain it's state. It can implement interfaces, inherit from other classes and allow inheritance.

My rule for choosing between static and singleton:

If there is a bunch of functions that should be kept together, then static is the choice. Anything else which needs single access to some resources, could be implemented as a singleton.

A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.

Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.

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:

if( useD3D )
    IRenderer::instance = new D3DRenderer
else
    IRenderer::instance = new OpenGLRenderer

Singleton's are instantiated. It's just that there's only one instance ever created, hence the single in Singleton.

A static class on the other hand can't be instantiated.

Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated. As far as I know static methods (static class must have static methods) are faster than non-static.

Edit:
FxCop Performance rule description: "Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.

Main differences are:

  • Singleton has an instance/object while static class is a bunch of static methods
  • Singleton can be extended e.g. through an interface while static class can't be.
  • Singleton can be inherited which supports open/close principles in SOLID principles on the other hand static class can't be inherited and we need to make changes in itself.
  • Singleton object can be passed to methods while static class as it does not have instance can't be passed as parameters

Distinction from static class

JDK has examples of both singleton and static, on the one hand java.lang.Math is a final class with static methods, on the other hand java.lang.Runtime is a singleton class.

Advantages of singleton

  • If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads.

  • Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded.

  • With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations.

  • Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can override methods defined in singleton class by extending it.

Disadvantages of static class

  • It is easier to write unit test for singleton than static class, because you can pass mock object whenever singleton is expected.

Advantages of static class

  • Static class provides better performance than singleton, because static methods are bonded on compile time.

There are several realization of singleton pattern each one with advantages and disadvantages.

  • Eager loading singleton
  • Double-checked locking singleton
  • Initialization-on-demand holder idiom
  • The enum based singleton

Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton

In an article I wrote I have described my point of view about why the singleton is much better than a static class:

  1. Static class is not actually canonical class – it’s a namespace with functions and variables
  2. Using static class is not a good practice because of breaking object-oriented programming principles
  3. Static class cannot be passed as a parameter for other
  4. Static class is not suitable for “lazy” initialization
  5. Initialization and using of static class is always hard tracked
  6. Implementing thread management is hard
  • Singleton class provides an object(only one instance) during the application lifeCycle such as java.lang.Runtime

    While Static class only provide static methods such as java.lang.Math

  • Static methods in Java cannot be overridden, but methods defined in Singleton class can be overridden by extending it.

  • Singleton Class is capable of Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. whereas static not.

For eg: java.lang.Runtime,is a Singleton Class in Java, call to getRuntime() method returns the runtime object associated with the current Java application but ensures only one instance per JVM.

  1. We can create the object of singleton class and pass it to method.

  2. Singleton class doesn't any restriction of inheritance.

  3. We can't dispose the objects of a static class but can singleton class.

A static class in Java has only static methods. It is a container of functions. It is created based on procedural programming design.

Singleton class is a pattern in Object Oriented Design. A Singleton class has only one instance of an object in JVM. This pattern is implemented in such a way that there is always only one instance of that class present in JVM.

Below are some main differences between static class and singleton:

1.Singleton is a pattern, not a keyword like static. So for creating a static class static keyword is sufficient while in the case of singleton there is a need to write the logic for the singleton.

2.A singleton class must have a private default instance constructor, while a static class cannot contain any instance constructor.

3.A static class is neither instantiated nor extended, while a singleton class can be.

4.A static class is sealed implicitly, but the singleton class must be decorated as sealed explicitly.

5.It is possible for a singleton to implement the interface or inherit from another class, but the static class neither implements the interface nor extends from any other class.

6.We cannot implement the dependency injection with a static class, but DI is possible with the singleton class because it can be interface driven. The scope of the static class is at the app domain level because it is managed by the CLR, while the scope of the singleton object is across the application lifecycle.

7.A static class cannot have any destructor but a singleton class can define a destructor.

8.The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.

A singleton is nothing more than a write-once static variable on a class that always refers to the same instance of itself once it's initialized.

So, you cannot "use a singleton instead of static variables" nor can you avoid keeping state in static variables by using singletons.

The advantage of a singleton is only this: it does not get reinitialized even if some other code tries to reinitialize it a thousand times. This is great for something like a network handler where, y'know, it would suck if an instance got replaced with another instance in the middle of waiting for a response.

Unless you want an entire app WITH NO INSTANCES ANYWHERE—all static!—then the singleton makes sense for these cases where we cannot rely on a lack of human error as the only guarantee something won't get overwritten.

But beware, singleton is no guarantee against state living everywhere. Your network handler may within itself also rely on other singletons, etc. Now we have state living in a host of singletons... marvelous.

And there is no compiler in existence that will ensure that the singleton is where all your state lives, or any other such ideas, at compile time. You can have a hundred static variables on a class that has a singleton. And the singleton can access the static variables. And the compiler will not care.

So I would caution anyone from assuming that using a singleton guarantees anything at all about where state lives. Its only guarantee is simply that it is the only instance of its class, ever. And that is also its only advantage.

Any other advantages that the other answers claim for singletons are things the compiler does not guarantee and that may vary from language to language. Dependency injection is a supplementary pattern that may rely on a singleton, though it may or may not be the best solution or the only solution in a given language. In languages that lack generics, or that place arbitrary restrictions on calling static accessors and functions, resorting to the singleton pattern may indeed be the best available solution to a given problem.

Singleton is not necessary at all in a language like Swift, to get dependency injection, testable code, well-managed state, thread-safe accessors, polymorphism, etc. However it's still useful for the guarantee of a single instance ever.

To recap: a singleton is nothing more than a static variable that serves as a safeguard against multiple instances of given class existing, and against the single instance being overwritten by a new one. That's it, period, full stop.

Example with a static class

public class Any {

    private static Any instance = new Any();

    private Singleton() {
        System.out.println("creating");
    }
}

with singleton patterns only exist one instance:

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {
        System.out.println("creating");
        if (instance != null) {
            throw new RuntimeException("Imposible create a new instance ");
        }
    }
}

static classes usually are used for libraries, singletons are used if I need only one instance of a particular class. From the point of view of memory there are some differences though: usually in the heap there are allocated only objects, the only methods allocated are methods that are current running. a static class has all methods static too and that will be in the heap from begin, so in general the static class consume more memory.

Related