单例模式


单例模式的本质就是关闭该类的构造方法,只有通过其他方法进行创建该对象,并且保存一个静态属性,判断该对象是否创建过,如果创建则赋值给该属性,再次使用就直接返回该属性值。单例模式根据加载时间分为懒汉式和饿汉式,即启动时加载为饿汉式,使用时加载为懒汉式。但是随着逐渐完善和需求的提升,该模式也进行了并发问题的解决。以下为几种实现方式:

1. 懒汉式,线程不安全

public class Singleton {
    private static Singleton instance;
    // 关闭构造方法
    private Singleton (){}
    // 构建对象方法,使用时判断是否已经创建
    public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
    }
}

2. 懒汉式,线程安全

public class Singleton {
    private static Singleton instance;
    private Singleton (){}
    // 加锁解决并发问题,但是影响性能
    public static synchronized Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
    }
}

3. 饿汉式

public class Singleton {
    // 程序启动时创建对象
    private static Singleton instance = new Singleton();
    private Singleton (){}
    public static Singleton getInstance() {
    return instance;
    }
}

4. 双检锁/双重校验锁(DCL,即 double-checked locking)

public class Singleton {
    // volatile变量规则:对一个变量的写操作先行发生于后面对这个变量的读操作
    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;
    }
}

5. 登记式/静态内部类

public class Singleton {
    private static class SingletonHolder {
    private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}
    public static final Singleton getInstance() {
    return SingletonHolder.INSTANCE;
    }
}

6. 枚举

public enum Singleton {
    INSTANCE;
    public void whateverMethod() {
    }
}

总结

一般情况下,不建议使用第 1 种和第 2 种懒汉方式,建议使用第 3 种饿汉方式。只有在要明确实现 lazy loading 效果时,才会使用第 5 种登记方式。如果涉及到反序列化创建对象时,可以尝试使用第 6 种枚举方式。如果有其他特殊的需求,可以考虑使用第 4 种双检锁方式。