1) Ensure a class has only one instance, and provide a global point of access to it.
2) 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.
1) Provide a default Private constructor.
2) Create a Method for getting the reference to the Singleton Object.
3) Make the Access method Synchronized to prevent Thread Problems.
4) Override the Object clone method to prevent cloning.
1) 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.
2) 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.
1) 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();
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?