1. 懒汉式
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
优点:
实现了懒加载,避免了内存的浪费
缺点:
必须加锁才能保证单例,但是加锁会影响效率
2. 饿汉式
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
优点:
不加锁,执行效率高,在类加载时候就进行了实例的初始化,不会出现多线程冲突
缺点:
未实现懒加载,类加载就进行了初始化,造成了内存浪费
3. 双重检查锁
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
优点:
实现了延迟加载,线程安全,效率高
缺点:
实现难度较高
4. 静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static final Singleton getInstance() {
return SingletonHodlder.INSTANCE;
}
}
优点:
显示调用getInstance方法时候才会装在SingletonHolder类,实现了延迟加载,线程安全
单例模式
最新推荐文章于 2023-07-26 15:46:48 发布