单例模式的几种实现方法,具体如下:
懒汉模式
public class Singleton{
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return 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 Singleton getInstance(){
if (instance == null){
synchronized (Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
优点
- 多线程安全
- 延迟加载
缺点
- 同步耗时
静态内部类
public class Singleton {
private Singleton(){}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
}
优点
- 多线程安全
- 延迟加载
- 耗时短(与双重检查相比)
用缓存实现
public class Singleton {
private static final String KEY = "instance";
private static Map<String, Singleton> map = new HashMap<>();
private Singleton(){}
public static Singleton getInstance(){
Singleton singleton ;
if (map.get(KEY) == null){
singleton = new Singleton();
map.put(KEY, singleton);
} else {
singleton = map.get(KEY);
}
return singleton;
}
}
优点
- 线程安全
缺点
- 占用内存较大
枚举模式
public enum Singleton {
instance;
public void operate(){}
}
优点
- 简洁
缺点
- 占用内存大(Android官方不推荐使用枚举)
重要说明
想随时获取最新博客文章更新,请关注公共账号DevWiki,或扫描下面的二维码:
评论区