The major differences between Static Class and Singleton Class are below :
Static Class | Singleton Class |
---|---|
Instances cannot be created | Only one instance is created of a Singleton class in the class itself |
Static class can have only static Constructor. | Singleton class can have private constructor. |
Static class is automatically loaded by the CLR. | Singleton class is lazy loaded means it is created when user requests. |
Inheritance of Static class is not allowed. | As it contains a private constructor so you cannot inherit your singleton class but if you make it protected than you can inherit it but the base class will no more remain a Singleton Class. |
Static class cannot implement Interfaces. | Interfaces can be implemented here. |
Passing to method: We cannot pass static class to method. | The instance of Singleton class can be passed to a method. |
public static class A { ……// only static members public static method1(){…..} } public B() { A obj = new A(); //error- cant create obj of static class A.method1(); // method1 is accessed by class name } |
public class SingletonExample { private static SingletonExample obj; private SingletonExample(){} public static SingletonExample Obj { get { if (obj == null) { obj = new SingletonExample(); } return obj; } } } |
Take a Glance :
Singleton class only can create its own instance and restricting any other classes to create its instance, It is achieved by declaring the constructor private.
Many students asks me that i can make the constructor public or protected then also no error comes. So all those friends out there i want to ask you that you are creating Singleton Class so you must follow the Pattern. If you make it of other scope(not private) then you are not creating a singleton class.The example given above is not thread safe, but you make it by creating a lock in the property.(take all the code in lock which is in get{…..}).