Step 1: Provide a default Private constructor
public class Singleton { |
Step 2: Create a Static Method for getting the reference to the Singleton Object
public class Singleton { |
Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized Singleton getInstance()
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 declarationStep 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();
}
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class Singleton { Singleton obj = Singleton.getInstance(); |
Another approach
We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass { |
But still there are some issues left.
Protected vs Private Constructor
protected Singleton() {
// ...
}
The constructor could be made private to prevent others from instantiating
this class. But this would also make it impossible to create instances of
Singleton subclasses.
No comments:
Post a Comment