Difference Between Singleton Class vs. Static Class

Difference Between Singleton Class vs. Static Class


singleton-vs-staticclass

In the IT interview, Static Class vs. Singleton is a very common interview question. Today we will see the similarities and differences between them. We will also see, why this question is being asked by the interviewer so frequently.

Today's Agenda

Q01. What is Static Class? Q02. What are the core features of the Static Classes? Q03. What are the fundamental rules of the Static Classes? Q04. What is Singleton? Q05. What are the different types of Singleton? Q06. What are the different ways to implement a Singleton? Q07. What are the core components of a Singleton Class? Q08. What are the similarities between Static Class vs. Singleton? Q09. What is the difference between Singleton vs. Static Class?

Introduction

The "Singleton Class vs. Static Class" or "Static Class vs. Singleton Class" is a very famous interview question of the interviewer. They have so many interesting similarities and differences. Today we will see all of them in detail. A static class is a class that contains only static members. It cannot be instantiated or inherited by other classes. On the other hand, a singleton class is a class that can have only one instance and provides a global point of access to it.

What is Static Class?

In C#, a static class is a special class that has features of both an abstract class and a sealed class, since an abstract class cannot be instantiated and a sealed class can not be inherited. When a class is declared as static, it is sealed and abstract by default. Please read more about the static class here. The concept of a static class was introduced in C# 2. A class declared with the static modifier is known as a static class. All the members of a static class are always static in nature as the static class can only contain static data members, static methods, and static constructors. A static member cannot be accessed by the class object. A Static class is loaded automatically by the CLR when the program containing the static class is loaded. In C#, classes, constructors, methods, variables, properties, events, and operators can be defined as static. However, the interface (until C# 8 ), structure, indexers, enum, and destructors or finalizers cannot be declared as static.

What are the core features of the Static Classes?

  1. A static class is loaded by the CLR when the program that references the static class is loaded.
  2. A program or user cannot specify exactly when the static class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and it's static constructor is called before the class is referenced for the first time in your program.
  3. The static class lives in the High-Frequency Heap (HFH) for the lifetime of the App Domain in which the program resides.
  4. Only a single copy of static class and static members exists, regardless of how many instances of the class are created.
  5. A static class can contain const field members but a const field cannot be declared static explicitly because a const field is static implicitly and it belongs to the type, not to instances of the type.
  6. All the static members can only be accessed by the Class Name itself, not by the instance of the class.
  7. Enums can be defined without the static keyword in the static class since it is sealed and static implicitly by default. Therefore an enum can be directly accessed by the class name itself.

What are the fundamental rules of the Static Classes?

  1. Static classes cannot be instantiated like normal concrete classes because static classes are abstract implicitly by default.
  2. The static classes cannot be inherited because static classes are sealed implicitly by default.
  3. A static class cannot be marked as sealed because a static class is sealed by default.
  4. A static class can only contain a static constructor without any access modifiers.
  5. A static class can contain only static data members, except const and enum.
  6. Static classes cannot have explicit destructors or finalizers.
  7. Indexers cannot be defined in a static class since an indexer cannot be static because "this" pointer is not allowed for referencing static members.
  8. A static class cannot contain any instance members or instance constructors since instantiation is not allowed.
  9. The contextual keyword "var" cannot be used to define any static members. You must have to specify a type of member explicitly after the static keyword.
  10. A static class cannot inherit from any class except the "System.Object" class. Since "Object" is the ultimate base class of all the .NET Classes; it is the root of the type hierarchy.

What is Singleton?

Singleton design pattern is one of the most popular design patterns. In this pattern, a class has only one instance in the program that provides a global point of access to it. A singleton class is a creational design pattern that restricts the instantiation of a class to a single instance hence the name "singleton". It ensures that only one instance of the class exists in the application and provides a global point of access to that instance. Please read more about the singleton class here. The creational design patterns are design patterns that deal with object creation and instantiation mechanisms. This pattern helps us to centralize the object creation logic and depending upon the condition, it will create, initialize, and return the appropriate object to the client. The Singleton Pattern was originally introduced in the famous book "Design Patterns: Elements of Reusable Object-Oriented Software" of "Gang of Four" by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. It ensures that one and only one persistent object exists and has a single point of access to it. A singleton pattern is also called an Anti-Pattern. According to the GoF: "Ensure a class only has one instance, and provide a global point of access to it."

What are the different types of Singleton?

There are basically four types of singleton:

  1. Thread-Safe Singleton
  2. Non-Thread Safe Singleton
  3. Lazy-Loaded Singleton
  4. Eagerly-Loaded Safe Singleton

What are the different ways to implement a Singleton?

Based on the above categories, there are various ways to implement a singleton pattern:

  1. Non-Thread Safe Singleton
  2. Thread-Safe Singleton using lock
  3. Thread-Safe Singleton using Double-Check locking
  4. Thread-Safe without a lock
  5. Lazy-Loaded and Thread-Safe Singleton using .NET 4's Lazy<T> type
  6. Eagerly-Loaded and Thread-Safe Singleton using Static Constructor
  7. Fully Lazy-Loaded Singleton using Nested Class

What are the fundamental core components of a Singleton Class?

There are four fundamental components of a singleton pattern implementation:

  1. A Sealed Class that contains the logic of singleton and prevents the further inheritance
  2. A single private default constructor that prevents the inheritance and instantiation
  3. A Static variable that holds the reference of the singleton instance
  4. A public and static method or property for getting the reference to the created singleton instance

  
public sealed class Singleton
{
    private static readonly Singleton _instance = null;

    private Singleton() {}

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
            	_instance = new Singleton();
            }
            return _instance;
        }
    }
}
  

What are the similarities between Static Class vs. Singleton?

Before looking into the "Singleton vs. Static Class", let's see the similarities between them so that we can understand why the interviewer asks this question so frequently:

  1. Both the static class and singleton class have one and only one instance throughout the whole application.
  2. Both can be used for having a single global state and accessibility of the application.
  3. Both provide thread safety as well as a singleton can also be implemented as thread-safe.
  4. Both static classes and singleton are not garbage collected.
  5. Both static class and singleton can be cloned very easily.
  6. Both static class and singleton can have static members.

What is the difference between Singleton vs. Static Class?

Both Static Class and Singleton Class have only one instance available in the memory and both are used for holding the global state of the application. However, the following are the main differences between static class vs. singleton:

Singleton Class vs. Static Class
Sr. No. Singleton Class Static Class
1. A singleton class can implement the interface and inherit from another base class. On the other hand, a static class neither implements the interface nor extends from any other class.
2. A Singleton can be used for dependency injection is possible with the singleton class because it can be interface driven. However Static classes can not be used for dependency injection as they can not implement the interface.
3. The singleton class object can be passed as a parameter to another method or constructor. But a static class cannot be passed as a parameter because it's instance cannot be created programmatically.
4. A singleton class can have a destructor and can implement the IDisposable Interface. On the other hand, the static classes are not allowed to define any destructor as they are handled by the CLR internally.
5. The scope of the singleton object is across the application lifecycle once it is created. The scope of the static class is at the app domain level because it is managed by the CLR itself.
6. We have full control over the singleton instance creation and destroy programmatically. On the other hand, we do not have any control over a static class because it is instantiated and managed by the CLR internally.
7. Singleton objects can be injected by the DI Injector in the IoC Container. However, a static instance cannot be injected by any DI Injector as manual instance creation is not possible programmatically.
8. Usually, a singleton class must have a private default instance constructor so that no one can create the instance manually or extend it. On the other hand, it is not required for a static class because instance constructors are not allowed in a static class. Also, a static class is sealed and abstract by default.
9. Singleton classes can be serialized for REST API. On the other hand, static classes cannot be serialized.
10. Singleton classes can have both static and instance members. On the other hand, a static class can have only static members.
11. Singleton is an anti-pattern as it does not follow the Single Responsibility Principle of SOLID. On the other hand, a static class is not a user-defined design pattern.
12. Singleton can be used for Dependency Inversion. On the other hand, static classes cannot be used for Dependency Inversion.
13. Last but not least the singleton is a pattern not a keyword like static. We have to write the logic of the singleton pattern. On the other hand, the statics is a keyword that does all the things for us internally.

Conclusion

In short, a static class is used to group the related methods and properties that do not require an instance of the class to be created, while a singleton class is used to ensure that only one instance of a class is created and to provide a global point of access to it. Also, a static class is neither instantiated nor extended while a singleton class can be. We cannot implement the DI with a static class but DI is possible with the singleton because it can be interface driven. There are so many different ways to implement the singleton but only one standard way to create a static class.


Recommended


Thanks for visiting this page. Please follow and join us on LinkedIn, Facebook, Twitter, Telegram, Quora, Instagram, WhatsApp, Tumblr, VK, Pinterest, and YouTube for regular updates.

Post a Comment

Please do not attach any link in the comment box.

Previous Post Next Post