1.通过序列化方式
通过将实例序列化后写入文件中,再读取文件中的对象会破坏单例模式
public class SerializeFunction {
public static void main(String[] args) throws Exception {
// writeObj2File();
readObjFromFile();
readObjFromFile();
}
public static void readObjFromFile() throws Exception {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D://a.txt"));
SinglePatten s1 = (SinglePatten) objectInputStream.readObject();
System.out.println(s1);
objectInputStream.close();
}
public static void writeObj2File() throws Exception {
SinglePatten instance = SinglePatten.getInstance();
ObjectOutputStream outputStreamWriter = new ObjectOutputStream(new FileOutputStream("D://a.txt"));
outputStreamWriter.writeObject(instance);
outputStreamWriter.close();
}
}
输出结果:
TestClass.ch1.SinglePatten.Destroy.Serialize.SinglePatten@5b6f7412
TestClass.ch1.SinglePatten.Destroy.Serialize.SinglePatten@27973e9b
Process finished with exit code 0
返回的2个对象的地址不相同,因此单例模式被破坏
2.反射方式破坏
通过反射的方式创建对象会破坏单例模式
public class TestMain {
public static void main(String[] args) throws Exception {
//1.获取类字节码
Class clazz = SinglePattenLazy.class;
//2. 获取无参构造函数对象
Constructor con = clazz.getDeclaredConstructor();
//3. 由于无参构造函数是private,设置访问权限
con.setAccessible(true);
//4. 通过构造方法,反射生成对象
SinglePattenLazy s1 = (SinglePattenLazy) con.newInstance();
SinglePattenLazy s2 = (SinglePattenLazy) con.newInstance();
System.out.println(s1);
System.out.println(s2);
}
}
输出结果:
TestClass.ch1.SinglePatten.SinglePattenLazy@1b6d3586
TestClass.ch1.SinglePatten.SinglePattenLazy@4554617c
可以看到2个类的地址不同,因此单例模式被破坏