今天在看了一个博文,看到Java中单例模式的实现问题,称为最佳的单例模式实现,但是和平时自己写的是不同的,遂不知己的单例模式与汝的单例模式有何不同之处:
先来上别人的单例模式最佳实现:
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 {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
自己平时写的实现:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
两种方式的比较:为什么第一种成为最佳的实现?????