Singleton Design Pattern Without Cloning Java - Java @ Desk

Tuesday, June 4, 2013

Singleton Design Pattern Without Cloning Java

Issues with basic version of Singleton pattern design:
1) It could happen that SingletonPattern.getSingletonPatternObject() call may occur from 2 different places in an application at the same time and 2 objects get created which will violate the principal of the pattern

2) Consider the code
SingletonPattern clonedSingletonPattern = (SingletonPattern) obj.clone();
This code will create the copy of the singleton object which again violates the design patters implementation

Click Singleton Pattern Java With Double Locking and Without Cloning for complete version of Singleton Design Pattern

To avoid above issues here is an improved version

public class SingletonPattern {

    // Make the constructor private so that it cannot be instantiated outside the class
    private SingletonPattern() {

    }

    // Variable for SingletonPattern class
    private static SingletonPattern singletonPattern;

    // Method to get the instance of SingletonPattern class
    public static synchronized SingletonPattern getSingletonPatternObject() {
        if (singletonPattern == null) {
            singletonPattern = new SingletonPattern();
        }
        return singletonPattern;
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Thrown this exception in order to avoid the creation of copy of this object");
    }
}








No comments:

Post a Comment