Java 如何实例化Bill Pugh方法中实现的单例类?
嗨,有人能告诉我如何实例化下面给定的单例类的正确方法吗Java 如何实例化Bill Pugh方法中实现的单例类?,java,Java,嗨,有人能告诉我如何实例化下面给定的单例类的正确方法吗 public class BillPughSingleton { private BillPughSingleton(){} private static class SingletonHelper{ private static final BillPughSingleton INSTANCE = new BillPughSingleton(); } public static
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
尝试:
BillPughSingleton bill = BillPughSingleton.getInstance();
尝试:
BillPughSingleton bill = BillPughSingleton.getInstance();
您可以像这样简单地重写类,不再需要
SingletonHelper
class
public class BillPughSingleton {
private static BillPughSingleton INSTANCE;
private BillPughSingleton(){}
public static BillPughSingleton getInstance(){
if (INSTANCE==null) {
INSTANCE = new BillPughSingleton();
}
return INSTANCE;
}
}
对于instansiate,您可以尝试以下方法:
BillPughSingleton instance = BillPughSingleton.getInstance();
您可以找到更多的另一个示例您可以像这样简单地重写您的类,不再需要
SingletonHelper
类
public class BillPughSingleton {
private static BillPughSingleton INSTANCE;
private BillPughSingleton(){}
public static BillPughSingleton getInstance(){
if (INSTANCE==null) {
INSTANCE = new BillPughSingleton();
}
return INSTANCE;
}
}
对于instansiate,您可以尝试以下方法:
BillPughSingleton instance = BillPughSingleton.getInstance();
你可以找到更多的另一个例子你不能让
类加载器
帮你完成这项工作。我不太明白你在这里的要求。这里有一个非常好的实现的单例模式(尽管实际上并不需要内部类SingletonHelper
)。你能进一步描述一下你遇到的问题吗?你不能让Classloader
帮你完成这项工作。我不太明白你在问什么。这里有一个非常好的实现的单例模式(尽管实际上并不需要内部类SingletonHelper
)。你能进一步描述一下你遇到的问题吗?