Steps to Create
Default constructor is made private [It prevents the direct instantiation of the object by others (Other Classes).
A static modifier is applied to the instance method that returns the single object [can be accessed without creating an object]
synchronization is only needed during initialization on singleton instance[To prevent creating another instance of Singleton]
Example
package com.javalearning.crazy;
public class SingletonObject {
private static SingletonObject singletonObj = null;
private SingletonObject()
{
}
public static synchronized SingletonObject getInstance() {
if (singletonObj == null) {
singletonObj = new SingletonObject();
}
return singletonObj;
}
public static void main(String[] args) {
SingletonObject singletonObj = null, singletonObj1 =null;
singletonObj = SingletonObject.getInstance();
singletonObj1 = SingletonObject.getInstance();
System.out.println(singletonObj+"="+singletonObj1);
}
}
Benefits
Singletons can be used to create a Connection Pool.
lazy loading - instance is created only when client calls getInstance() [method is loaded before instance created]
Drawbacks
Need to be cautious in multi threaded environment.
We can still be able to create a copy of the Object by cloning
No comments:
Post a Comment