用JAVA实现深复制

Resume 简历类

package com.springboot.girl.design.prototype;

import lombok.Data;

/**
 * @Description 简历
 * @Date 2019/6/26
 */
@Data
public class Resume implements Cloneable{
    private String name;
    private int age;
    private WorkExperience workExperience;

    public Resume(String name, int age, WorkExperience workExperience) {
        this.name = name;
        this.age = age;
        this.workExperience = workExperience;
    }

    @Override
    protected Resume clone() throws CloneNotSupportedException {
        Resume resume = (Resume) super.clone();
        WorkExperience we = resume.getWorkExperience();
        resume.setWorkExperience((WorkExperience) we.clone());
        return resume;
    }

    @Override
    public String toString() {
        return "Resume{" + "name='" + name + '\'' + ", age=" + age + ", workExperience=" + workExperience + '}';
    }
}

WorkExperience

package com.springboot.girl.design.prototype;

import lombok.Data;

/**
 * @Description TODO
 * @Date 2019/6/26
 */
@Data
public class WorkExperience implements Cloneable{
    private String unitName;
    private String workTime;

    public WorkExperience(String unitName, String workTime) {
        this.unitName = unitName;
        this.workTime = workTime;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "WorkExperience{" + "unitName='" + unitName + '\'' + ", workTime='" + workTime + '\'' + '}';
    }
}

TestMain

package com.springboot.girl.design.prototype;

/**
 * @Description TODO
 * @Date 2019/6/26
 */
public class TestMain {

    public static void main(String[] args) throws CloneNotSupportedException {
        Resume r1 = new Resume("张三",23,new WorkExperience("联创","2016-2018"));
        Resume r2 = r1.clone();
        r2.getWorkExperience().setUnitName("投哪");
        r2.getWorkExperience().setWorkTime("2018-2019");
        System.out.println(r1);
        System.out.println(r2);
    }
}

 

运行结果

Resume{name='张三', age=23, workExperience=WorkExperience{unitName='联创', workTime='2016-2018'}}
Resume{name='张三', age=23, workExperience=WorkExperience{unitName='投哪', workTime='2018-2019'}}

你可能感兴趣的:(基础)