1. 定义
一个类仅有一个实例,并提供一个访问它的全局访问点
2. 应用场景
工具类,线程池,日志对象,缓存
3. 优点
提供对唯一实例的受控访问
只存在一个对象,节约系统资源
4. 缺点
不是抽象的,拓展性差
共享过多,比如连接池,连接数不够用
长时间不使用,被垃圾回收
5. Sping 中的应用
Spring 中的依赖注入中应用了单例,
其中的方法 getSingleton() 实现了懒汉式。
在配置文件中配置注册bean对象的时候**「设置scope的值为singleton」**
6. 代码
6.1. 饿汉
静态属性或静态代码初始化单例对象;
JVM加载 class 时实例化对象。
public class Singleton {
private static final Singleton INS = new Singleton();
private Singleton() {}
public static Singleton getInstance() {return INS;}
}
public class Singleton {
private static final Singleton INS;
static {
INS = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {return INS;}
}
6.2. 懒汉
获取对象时,实例化对象;
对象需要使用 volatile 关键字,避免因指令重排序造成的,返回了对象地址,但对象尚未创建的问题;
使用同步代码块来实例化对象;
两次 null 值判断,同步代码块内外各进行一次 null 值判断,避免并发问题。
public class Singleton {
private static volatile Singleton INS;
private Singleton() {}
public static Singleton getInstance() {
if (null == INS) {
synchronized(Singleton.class) {
if (null == INS) {
INS = new Singleton();
}
}
}
return INS;
}
}
6.3. 静态内部类
获取对象时,加载内部类,执行内部类的静态代码。
public class Singleton {
private Singleton() {}
private static class Inner {
private static final Singleton INS = new Singleton();
}
public static Singleton getInstance() {
return Inner.INS;
}
}
6.4. 枚举
public enum Singleton {
INS;
}