Wednesday, April 20, 2011

What is difference between static class and singleton

Singleton and Static classes both provide a central point of access i.e. there's only one instance and one way to access it.

The benefit of Singleton class is it is much more flexible that static classes. Static classes once defined could not accomodate any future design changes as by design static classes are rigid and cannot be extended.

Singleton on the other hand provides flexibility and also provides sort of a mechanism to control object creation based on various requirements. They can be extended as well if need arises. In other words you are not always tied to a particular implementation. With Singleton you have the flexibility to make changes as when situation demands.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes), so you can pass around the singleton as if it were "just another" implementation.

In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.

Quick Example:

if( useD3D )
IRenderer::instance = new D3DRenderer
IRenderer::instance = new OpenGLRenderer

A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.

Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.

A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

A static class allows only static methods.

a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

If there are bunch of functions should be kept together, then static is the choice. Anything else which needs single access to some resources, could be implemented singleton.

Compiled By Rajesh Rolen

Share This!


Chhatrapati said...

you told that we can't extend static class
if i add a static member or static method in that class then what's the prob in it.

chhatrapati said...

ok ok sorry for that comment
i was confused with extend word

Powered By Blogger · Designed By Seo Blogger Templates