Bill Pugh 单例的建议实现看起来像
// 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;
}
}
但是我们可以直接将顶级类中的实例变量设置为 final 和 static,而不是创建嵌套静态类,无论我们调用多少次getInstance,它总是返回唯一的单例对象:
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");
}
}
那么嵌套类的意义何在?