Singleton and static classes are both C# design patterns for implementing specific functionality in a software application. However, they differ significantly in terms of their purpose, implementation, and application.
Singleton
- The Singleton pattern guarantees that a class has only one instance while providing a global access point to this instance.
- When a single instance of a class must be shared across the entire application, a singleton class is used.
- A Singleton class is instantiated using a private constructor and a static instance property. The instance property is used to access the single instance of the class.
Example
public sealed class Singleton { private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() {} public static Singleton Instance { get { lock(padlock) { if (instance == null) { instance = new Singleton(); } return instance; } } } }
Static Classes
A static class is one that only has static members and cannot be instantiated.
Static classes are used when a class is only required to provide a collection of utility or helper methods and no instances of the class are required.
Example
public static class Utilities { public static int Add(int a, int b) { return a + b; } public static int Subtract(int a, int b) { return a - b; } }
To summarise, the Singleton pattern ensures that a class has only one instance and provides a global point of access to it, whereas the static class is used to create utility classes that only have static members.