Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM
• Ensure a class has only one instance, and provide a global point of access to it.
• Encapsulated "just-in-time initialization" or "initialization on first use".
Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.
Requirements to create a singleton object in Java :
• Provide a default Private constructor.
• Create a Method for getting the reference to the Singleton Object.
• Make the Access method Synchronized to prevent Thread Problems.
• Override the Object clone method to prevent cloning.
Step 1: Create a class Singleton
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.
Step 5: Create class SingletonObjectDemo to test the Singleton pattern
Run the given class as java Application and we will get the output
Note : To prove that only one object has been created for the Singleton class and if we try to make another one in SingletonObjectDemo class what will happen?
Sometimes in distributed systems, we need to implement Serializable interface in Singleton class so that we can store it’s state in file system and retrieve it at later point of time. Here is a small singleton class that implements Serializable interface also.
Step 1: Create a Singleton class with serialization
Step 2: Create a class to test that serialized singleton object persist or not.
Step 3: Run the Test Program to see output
This proves that singleton Object is not preserved while Deserialization, because both of the instances have different hashCode.
So it destroys the singleton pattern, to overcome this scenario all we need to do it provide the implementation of readResolve() method.
After this you will notice that hashCode of both the instances are same in test program.