View RSS Feed

Design Patterns

Early instantiation using implementation with static field

Rate this Entry
by , 03-09-2012 at 06:48 PM (900 Views)
The singleton object gets instantiated in case the class gets loaded & is not when it is used first, in the given implementation. This happens because the instance member has been declared static. Thatís why there is no need of synchronization of any part of the code, in such cases. Class gets loaded once when the uniquity of the object is guaranteed.
Java Code:
//Early instantiation using implementation with static field.
class Singleton
{
	private static Singleton instance = new Singleton();
	private Singleton()
	{
		System.out.println("Singleton(): Initializing Instance");
	}
	public static Singleton getInstance()
	{    
		return instance;
	}
	public void doSomething()
	{
		System.out.println("doSomething(): Singleton does something!");
	}
}

Submit "Early instantiation using implementation with static field" to Facebook Submit "Early instantiation using implementation with static field" to Digg Submit "Early instantiation using implementation with static field" to del.icio.us Submit "Early instantiation using implementation with static field" to StumbleUpon Submit "Early instantiation using implementation with static field" to Google

Comments