通过反序列化机制会破坏单例类的规则
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;class Singleton implements Serializable { private static Singleton instance; private String name; private Singleton(String name) { this.name = name;
} public boolean equals(Object obj) { if (this == obj) { return true;
} if (obj.getClass() == Singleton.class) {
Singleton target = (Singleton) obj; return target.name.equals(this.name);
} return false;
} public static Singleton getInstance(String name) { if (instance == null) {
instance = new Singleton(name);
} return instance;
} public int hashCode() { return name.hashCode();
}
}public class SingletonTest { public static void main(String[] args) {
&