Search This Blog

Tuesday, March 25, 2008

SINGLETON vs STATIC

The Singleton pattern is useful when the object itself needs to keep some state.If no such thing is needed, a static method can do the job as well.

A purely static class can save state as well. Static variables can be used to store state.A static block can be used to initialize state. Static methods can be used to access or modify the state.AFAIK, the only think a purely static class cannot do is to force parameterization of the initialization of the class, since any method call can trigger the static initialization block. Such forced parameterization can be provided in the singleton by only providingan .instance() method with the desired arguments in the parameter list.

the Singleton pattern in that a Singleton class is supposed to have one (and only one) *instance*, while a "static class" is never instanciated (or, at least, there is no point in instanciating it).
a class full of static methods can't be polymorphic, but a singleton can.

The Singleton pattern has several advantages over the "static class" pattern. First, a singleton can extend classes and implement interfaces, while a static class cannot (well, it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously whilea static class is generally initialized when it is first loaded. A sinlgeton class can be extended and it's methods overidden. Perhaps the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance. For instance, assume you have a Configuration class that holds some global configs. Methods that use this configuration information may be defined as:

public void doSomething(Configuration config) {...}

3 comments:

Jaber Shabeek Noor Mohamed said...

pls refer this post:

http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/

Jaber Shabeek Noor Mohamed said...

pls see this post

http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/

Java programmer said...

From Java 5 onwards you can use Enum to implement Singleton pattern, its easy, its thread-safe and it handle Serialization by default. In fact its one of the easiest way of writing thread-safe singleton in Java