DP is a well-described solution to a common software problem. Its benefits:
- Already defined to solve a problem.
- Increase code reusability and robustness.
- Faster devlopment and new developers in team can understand it easily
DP defined in to 3 categories:
- Creational - Used to construct objects such that they can be decoupled from their implementing system.
- Structural - Used to form large object structures between many disparate objects
- Behavioral - Used to manage algorithms, relationships, and responsibilities between objects.
Creational:
- Singleton - Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the jvm.
We have different approaches for Singleton but all of these follow below bullets:
- Private constructor
- Private static variable of same class i.e. only instance of class.
- Public static method of class that returns the instance.
A few points to think about before implementation:
- You want eager initialization or lazy initialization of object.
- Exception handling of object if creation fails.
- Thread safety
- Reflection can break into this pattern. So, do you want to allow it or not.
- Serialization can destroy this pattern.
Keeping above points in mind we can implement over pattern. Below code depicts 2 such implementations and rest depends upon you to implement it differently or choose any of the one detailed below.
package
com.test.command.dp.creational.singleton;
public enum EnumSingleton {
INSTANCE;
public void aboutMe(){
System.out.println("Dinesh
Sachdev (Indore)");
}
}
|
package
com.test.command.dp.creational.singleton;
import
java.io.Serializable;
public class
SerializedSingleton implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1L;
private SerializedSingleton(){}
private static class SingletonHelper{
private static final
SerializedSingleton instance =
new
SerializedSingleton();
}
public static
SerializedSingleton getInstance(){
return SingletonHelper.instance;
}
protected Object
readResolve(){
return getInstance();
}
}
|
Comments
Post a Comment