1. to create only one object of a class at a time, and
2. that too the object can be created only by its own class.
Necessiates
1. The class' s constructor has to be declared 'private' . This makes the class to create its object by itself only.
2. The clone() method has to be overridden from the base class. This avoids the object to be cloned by any other class.
3. The instantiation (object creation) is done in its own method. And that method should be synchronized and should be declared static.
4. It is declared static because, only then the other classes can call the method without object.
Example:
class Singleton {
private static Singleton singletonObject;
// A private Constructor prevents any other class from instantiating.
private Singleton() {
// Optional Code
}
public static synchronized Singleton getSingletonObject() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
public class SingletonObjectDemo {
public static void main(String args[]) {
// Singleton obj = new Singleton(); Compilation error not allowed
//create the Singleton Object..
Singleton obj = Singleton.getSingletonObject();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}
No comments:
Post a Comment