Java中的对象拷贝-构建者模式

1)使用clone()方法,我们可以对其内的引用类型的变量,再进行一次 clone(),以此达到深拷贝效果。

public class DeepCopyTest {
    public static void main(String[] args) {
        Addr addr = new Addr("庞各庄");
        Person per1 = new Person(1002,"jack",addr);
        Person per2 = (Person) per1.clone();
        addr.setDesc("大兴岭");
        System.out.println(per1.getAddr());
        System.out.println(per2.getAddr());
    }
}
class Person implements Cloneable {
    private int id;
    private String name;
    private Addr addr;

    public Person(int id, String name, Addr addr) {
        this.id = id;
        this.name = name;
        this.addr = addr;
    }
    public Addr getAddr() {
        return addr;
    }
    @Override
    protected Object clone() {
        Person person = null;
        try {
            person = (Person)super.clone();   //浅拷贝
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        person.addr = (Addr)addr.clone();    //深拷贝
        return person;
    }

}
class Addr implements Cloneable {
    private String desc;

    public Addr(String desc) {
        this.desc = desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    @Override
    public String toString() {
        return "Addr{" +
                "desc='" + desc + '\'' +
                '}';
    }
    @Override
    protected Object clone() {
        Addr addr = null;
        try {
            addr = (Addr)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return addr;
    }
}

2)但如果引用类型里面还包含很多引用类型,或者内层引用类型的类里面又包含引用类型,使用clone方法就会很麻烦。这时我们可以用序列化的方式来实现对象的深拷贝

    void tstPrototype() throws CloneNotSupportedException, IOException, ClassNotFoundException {
        // tstPrototypeClone();
        // 使用ObjectInputStream ObjectOutputStream 处理拷贝问题,实现原型模式
        Resume resume = new Resume("peter", "male", 33, new Address("Losang", "kansasi", "jun"));
        System.out.println(resume.toString());


        //将该对象序列化成流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(resume);
        
        //将流序列化成对象
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Resume resumeObj = (Resume) objectInputStream.readObject();
        resumeObj.setName("里斯");
        resumeObj.setAddress(new Address());
        System.out.println(resumeObj);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值