You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public class Singleton {
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){};
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
单例模式类图展示:
下面要介绍的几种单例模式的实现方式:
饿汉式:
步骤一:
步骤二:
步骤三:
hello guy!
懒汉式-线程安全
懒汉式—线程不安全
双检锁(DCL,即 double-checked locking)
登记式
枚举
总结::一般情况下,不建议使用懒汉方式,建议使用饿汉方式(线程安全,但没有懒加载)。只有在要明确实现 lazy loading 效果时,才会使用登记方式。如果涉及到反序列化创建对象时,可以尝试使用枚举方式。如果有其他特殊的需求,可以考虑使用双检锁方式。
The text was updated successfully, but these errors were encountered: