Java设计模式 - 单例模式(创建型模式) (3)

默认只有枚举能保证序列化后对象仍相等,其它需要加readResolve()方法才能。

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.Path; import java.nio.file.Paths; public class TestSerializable { // 测试序列化后的对象是否相等 public static void main(String[] args) { Singleton5 s5_a = Singleton5.getInstance(); Singleton5 s5_b = Singleton5.getInstance(); System.out.println("序列化前:s5_a == s5_b ? " + (s5_a == s5_b)); Path file5 = Paths.get("object5.txt"); try (ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(file5.toFile()))) { out.writeObject(s5_a); } catch (Exception e) { e.printStackTrace(); } try (ObjectInputStream in = new ObjectInputStream( new FileInputStream(file5.toFile()))) { s5_b = (Singleton5) in.readObject(); } catch (Exception e) { e.printStackTrace(); } System.out.println("序列化后:s5_a == s5_b ? " + (s5_a == s5_b)); System.out.println(); Singleton6 s6_a = Singleton6.getInstance(); Singleton6 s6_b = Singleton6.getInstance(); System.out.println("序列化前:s6_a == s6_b ? " + (s6_a == s6_b)); Path file6 = Paths.get("object6.txt"); try (ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(file6.toFile()))) { out.writeObject(s6_a); } catch (Exception e) { e.printStackTrace(); } try (ObjectInputStream in = new ObjectInputStream( new FileInputStream(file6.toFile()))) { s6_b = (Singleton6) in.readObject(); } catch (Exception e) { e.printStackTrace(); } System.out.println("序列化后:s6_a == s6_b ? " + (s6_a == s6_b)); System.out.println(); Singleton7 s7_a = Singleton7.getInstance(); Singleton7 s7_b = Singleton7.getInstance(); System.out.println("序列化前:s7_a == s7_b ? " + (s7_a == s7_b)); Path file7 = Paths.get("object7.txt"); try (ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(file7.toFile()))) { out.writeObject(s7_a); } catch (Exception e) { e.printStackTrace(); } try (ObjectInputStream in = new ObjectInputStream( new FileInputStream(file7.toFile()))) { s7_b = (Singleton7) in.readObject(); } catch (Exception e) { e.printStackTrace(); } System.out.println("序列化后:s7_a == s7_b ? " + (s7_a == s7_b)); System.out.println(); } }

先把readResolve()方法注释掉;输出结果为:

懒汉式优化(Double Check Lock)双重校验锁,推荐用 序列化前:s5_a == s5_b ? true 序列化后:s5_a == s5_b ? false 饿汉式优化(静态内部类),推荐用 序列化前:s6_a == s6_b ? true 序列化后:s6_a == s6_b ? false 枚举,最好方法 序列化前:s7_a == s7_b ? true 序列化后:s7_a == s7_b ? true

加上readResolve()方法,枚举不需要,枚举甚至连Serializable接口都不需实现;输出结果如下:

懒汉式优化(Double Check Lock)双重校验锁,推荐用 序列化前:s5_a == s5_b ? true 序列化后:s5_a == s5_b ? true 饿汉式优化(静态内部类),推荐用 序列化前:s6_a == s6_b ? true 序列化后:s6_a == s6_b ? true 枚举,最好方法 序列化前:s7_a == s7_b ? true 序列化后:s7_a == s7_b ? true 使用场景

文件管理系统

日志记录类

与数据库的连接

应用实例

java.lang.Runtime#getRuntime()

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwfgsx.html