Recently I have came across a question what is the difference between Static and Singleton classes. So I thought it will be a good idea to share blog post about it.
Difference between Static and Singleton classes:
- A singleton classes allowed to create a only single instance or particular class. That instance can be treated as normal object. You can pass that object to a method as parameter or you can call the class method with that Singleton object. While static class can have only static methods and you can not pass static class as parameter.
- We can implement the interfaces with the Singleton class while we can not implement the interfaces with static classes.
- We can clone the object of Singleton classes we can not clone the object of static classes.
- Singleton objects stored on heap while static class stored in stack.
- A Singleton class can extend the classes(support inheritance) while static class can not inherit classes.
- Singleton class can initialize lazy way while static class initialize when it loaded first
- Static classes are sealed class while Single ton classes are not sealed.
This is a great list of differences between static and singleton class.
ReplyDeleteBut can you explain a bit more on static classes can't be passed as parameters.
Thanks for info!
DeleteThx..
ReplyDeleteYou're welcome
Deleteclone the object of Singleton classes means wt?
DeleteNow, My doubt is clear about Singleton and Static.
ReplyDeleteThanks
You're welcome
Deletehow static class are sealed class? we cant instantiate static class but sealed class can. And static class can contain only static members while in sealed class both static and non static allowed.
ReplyDeleteSealed class means you can not inherit classes into other class. Static classes can not be inherited so that's why its sealed.
DeleteBut in case of singleton class shouldn't the class be sealed.
DeleteI think for singleton, class should be sealed. Isn't I am correct.
DeleteYes you are correct. That's what I mentioned in my difference.
DeleteIn the 4th point I have reasons to agree that singleton objects would be stored on heap but can not digest that static class would be on stack. The stack can be overwritten once the function is finished executing and some another function is called.
ReplyDeleteCan you please help me digest this?
HI,
DeleteThere is a very good explanation why static classes are stored on stack.
http://stackoverflow.com/questions/1324348/where-does-clr-store-static-classes
Hope this will clear your argument. Static class scope is to application domain so there is not storage on heap.