最初的写法 在类中实现克隆方法 原型模式
可以重写equals和hashcode 反序列化出来的对象地址是不同的equals
User类
为了测试深拷贝,要在需要拷贝的类中加入引用类型
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class User implements Serializable {
private String username;
private String password;
}
Prototype类
package design.prototype;
import lombok.*;
import java.io.*;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class Prototype implements PrototypeSup, Serializable {
private String name;
private User user;
//序列化操作
@Override
public Object clone() {
//深拷贝
//创建流对象 ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
//序列化
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this); //当前这个对象以对象流的方式输出
//反序列化 bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
Prototype prototype = (Prototype) ois.readObject();
return prototype