Thursday, March 12, 2009

Explain about Singleton Class (CoreJava)

Question :Explain about Singleton Class (CoreJava)
Answer :In general, you use a singleton to enforce the notion that there will be
only one instance of a given class. Singletons should be used in situations
where creating more than one of something would be a logical error.
For example, a ConnectionPool would be a good place to use a singleton. If
clients could arbitrarily create ConnectionPools without regard to what
already exists, you would have a waste of resources. So you limit the
possible number of connection pools to 1 (per JVM), and you then know
that all clients are getting their connections from a single source.
Another example of Singleton use is for Object Factories. Say you have a
class called FooFactory that is responsible for fetching/saving Foo objects
to/from a database. You want to ensure that for each Foo record in the db,
there is only one corresponding Foo object floating around your
application. By centralizing all the creation logic in a single class, and
making that class a Singleton, you eliminate the possibility fo duplicate
The code that uses a connection obtained from the connection pool is
another matter. If all it does is do a getData() type operation, there is no
harm in having more than one of them.

No comments: