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 {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
单例的一种形式
最新推荐文章于 2025-04-04 02:48:17 发布
本文介绍了一种使用静态内部类实现的Java单例模式。通过这种方式可以在类加载时不会立即实例化,而是在第一次调用getInstance方法时创建。这种实现方式既实现了线程安全又避免了同步带来的性能影响。
2736

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



