单例模式保证了一个类只有一个实例,该类负责创建自己的唯一对象,并提供一个访问其对象的方法。
以下5种方式均保证了线程安全~
- 枚举, 实现简洁, 推荐
public enum Singleton {
INSTANCE;
public String sayHello() {
return "霸王喵~";
}
}
- 双检锁/双重校验锁, 实现复杂, 一般推荐
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
-
登记式/静态内部类, 效果与双检锁一样, 但实现更简单, 推荐
分析: 因为SingletonHolder
是静态内部类, 加载Singleton
时, 并不会加载SingletonHolder
,只有显式调用getInstance()
方法时,才会被装载,然后初始化INSTANCE
, 从而实现延迟加载的效果。
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
- 饿汉式, 非延迟加载, 不推荐
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
- 懒汉式, 性能低, 不推荐
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
网友评论