This article discuss about the differences between static class and singleton pattern.
Though both looks same and nearby achieve same functionality of maintaining single instance throughout the application but there are certain behavioral differences between two. Singleton is a design pattern that makes sure that your application creates only one instance of the class and internally uses static keyword.
Static | Singleton |
We don’t need to instantiate a static class and can access properties and methods with class name. |
Instance creation is necessary to access methods and properties. We create instance using static property defined for this purpose. |
Static class cannot be passed a parameter in another class |
We can pass instances of a singleton as a parameter to another class method. |
Static keyword is required in all the methods defined in Static class. |
The Singleton class does not require you to use the static keyword everywhere. |
Static class does not support interface inheritance. It throw error “static classes cannot implement interfaces” |
Singleton class can implement interface |
Static variable does not reset until server is restarted. |
|
It cannot have instance members. We need to call all the static methods explicitly. |
This may have instance members. |
//Static Class
public static class Stat{
static Stat(){
Console.WriteLine("static constr");
}
public static void Get(){
Console.WriteLine("stat method called");
}
}
//Singleton pattern
public class SingleTon{
private static SingleTon obj = null;
private static readonly Object locker = new Object();
private SingleTon(){
}
public int UserId {get;set;}
public static SingleTon GetInstance {
get{
if(obj == null){
lock(locker){
if(obj == null){
obj = new SingleTon();
}
}
}
return obj;
}
}
}