The right way to implement a Singleton Design Pattern, also written out by researcher Bill Pugh. Two major changes to keep in mind -
1. Make the initialization as lazy as possible.
2. Get rid of the issues of synchronized access.
Way to implement -
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
1. Make the initialization as lazy as possible.
2. Get rid of the issues of synchronized access.
Way to implement -
- Declare a public class, name it as Singleton.
- Create a private constructor for this class.
- Create an inner class which holds the singleton instance, make it private and static.
- Create a Singleton instance variable in inner class make it private, static and final and load new Singleton instance.
- Create a public static method in Singleton class to return the instance of Singleton class.
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
No comments:
Post a Comment