嗨,有人可以告诉我如何实例化下面给出的单例类的正确方法吗?
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
答案 0 :(得分:1)
尝试:
BillPughSingleton bill = BillPughSingleton.getInstance();
答案 1 :(得分:1)
你可以像这样重写你的课程,不再需要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();
您可以找到更多其他示例here