The suggested implementation of a Bill Pugh singleton looks like
// Java code for Bill Pugh Singleton Implementation
public class GFG
{
private GFG()
{
// private constructor
}
// Inner class to provide instance of class
private static class BillPughSingleton
{
private static final GFG INSTANCE = new GFG();
}
public static GFG getInstance()
{
return BillPughSingleton.INSTANCE;
}
}
But instead of creating a Nested static class, we can directly make the instance variable in the top class as final and static, no matter how many times we invoke getInstance
, it will always return the one and only singleton object :
public class SingletonBillPughMethod {
private SingletonBillPughMethod() {
}
private final static SingletonBillPughMethod SINGLE = new SingletonBillPughMethod();
public static SingletonBillPughMethod getInstance() {
return SingletonBillPughMethod.SINGLE ;
}
}
class Retrieve {
public static void main(String args[]) {
System.out.println(SingletonBillPughMethod.getInstance() + "==== 1");
System.out.println(SingletonBillPughMethod.getInstance() + "==== 2");
System.out.println(SingletonBillPughMethod.getInstance() + "==== 3");
}
}
So what's the point of the nested class?
Aucun commentaire:
Enregistrer un commentaire