Skip to main content

Posts

Showing posts from September, 2011

Singleton Class

Using Singleton class, we allow creation of asingle object only for a given class.
How to create it??

- Make constructor private
- Create a reference of class and make it static
- Call the constructor through a function which is public and static
- put condition inside this function to call the constructor only once by checking if the reference had been initialized or not.

Note: If we have two threads accessing the same code then it's possible that we get two objects in two different threads which are competing to get that object. So we can synchronize the code snippet inside the function for assuring the creation of a single object only.