package com.example.demo.designPattern.protoTypeMode;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.List;
/**
* @program: People
* @description:原型模式 浅拷贝 和 深度拷贝
* @author: liu wei ping
* @create: 2022-02-19 15:23
*/
@Data
@Slf4j
public class ConcreteProtoType implements Cloneable, Serializable {
private String name;
private int age;
private List<String> hobby;
//浅克隆 拷贝的是引用 使用父类的方法 反射创建对象赋值 内存地址不一样 改变其中一个对象的属性值,对应的
//原型对象属性值跟着变化
@Override
protected ConcreteProtoType clone() {
try {
return (ConcreteProtoType) super.clone();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//深度克隆 拷贝的是值 字节数组输出 出入流 拷贝对象 内存地址不一样 改变其中一个对象的属性值,对应的
//原型对象属性值不发生变化
public ConcreteProtoType deepClone() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream iis = new ObjectInputStream(bis);
return (ConcreteProtoType) iis.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
ConcreteProtoType concreteProtoType = new ConcreteProtoType();
concreteProtoType.setName("lwp");
concreteProtoType.setAge(20);
//List<String> hobby = Arrays.asList("书法", "编程");
List<String> hobby = Lists.newArrayList("书法", "编程");
concreteProtoType.setHobby(hobby);
ConcreteProtoType concreteProtoType1 = concreteProtoType.clone();
List<String> hobby1 = concreteProtoType1.getHobby();
hobby1.add("运动");
System.out.println(concreteProtoType);
System.out.println(concreteProtoType1);
System.out.println(concreteProtoType.equals(concreteProtoType1));
ConcreteProtoType concreteProtoType2 = concreteProtoType.deepClone();
List<String> hobby2 = concreteProtoType2.getHobby();
hobby2.add("运动");
System.out.println(concreteProtoType);
System.out.println(concreteProtoType2);
System.out.println(concreteProtoType.equals(concreteProtoType2));
}
}
Java实体类的深度克隆——原型模式
于 2022-02-19 16:02:08 首次发布