单例模式的特点
只允许有一个实例
单例类必须创建自己的实例
单例类必须向其他对象提供获取这一实例的方法
单例模式的实现方式
①懒汉式(线程不安全)
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
②懒汉式(线程安全)
加入synchronized 关键字
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized 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;
}
}
④饿汉式(静态内部类,线程安全)
使用内部类,在调用getInstance的时候才加载
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 enum Singleton {
INSTANCE;
public void whateverMethod() { }
}
//调用
class test{
public static void main(String []args){
Singleton.INSTANCE;
}
}
⑥懒汉式(双重校验锁 + volatile)
public class Singleton {
//volatile禁止指令重排序优化
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
//线程A与B,A先获取实例
if (singleton == null) {
//线程A获取实例的时候上锁
synchronized (Singleton.class) {
//线程A获取获取完释放锁,线程B判断返回null
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}