有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; } }
|