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 Object readResolve() {
return getInstance();
}
}
单例模式的最佳实现(Java)
最新推荐文章于 2023-08-05 20:43:43 发布
本文介绍了一种Java中实现单例模式的方法——懒汉式的具体实现方式。通过内部静态类SingletonHolder来持有Singleton实例,确保了线程安全且实现了延迟加载。
2321

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



