Java 中的单例模式完善实现 -Chathuranga


有3种主要情况会破坏Singleton,即使我们使它成为线程安全的

  • 克隆
  • 反序列化
  • 反射

下面单例代码可以避免:
class Singleton implements Cloneable, Serializable {

    private static Singleton instance = null;

    private Singleton() {
        if (instance != null) {
            throw new RuntimeException("You have broken Singleton class!");
        }
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    public Object readResolve() {
        return instance;
    }
    
}

class Singleton implements Cloneable, Serializable {

    private static Singleton instance = null;

    private Singleton() {
        if (instance != null) {
            throw new RuntimeException("You have broken Singleton class!");
        }
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    @Override
    public Object clone() {
        return instance;
    }

    public Object readResolve() {
        return instance;
    }
    
}