Implementing Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

 
Step 1: Provide a default Private constructor

public class SingletonObjectDemo {

	// Note that the constructor is private
	private SingletonObjectDemo() {
		// Optional Code
	}
}

Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonObjectDemo {

	private static SingletonObject singletonObject;
	// Note that the constructor is private
	private SingletonObjectDemo() {
		// Optional Code
	}
	public static SingletonObjectDemo getSingletonObject() {
		if (singletonObject == null) {
			singletonObject = new SingletonObjectDemo();
		}
		return singletonObject;
	}
}

We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

public static synchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Objectís clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Patternís objective. So to deal with this we need to override the Objectís clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

Transient Fields and Java Serialization

The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not part of the persistent state of the object and thus never saved during serialization.




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)