今天在看了一个博文,看到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;
}
}
两种方式的比较:为什么第一种成为最佳的实现?????
本文对比分析了Java中两种单例模式的实现方法,一种是经典的懒汉式单例,另一种被称为最佳实践的静态内部类单例。后者利用Java类加载机制确保线程安全和延迟加载,避免了同步带来的性能开销。
383

被折叠的 条评论
为什么被折叠?



