《大话设计模式》--原型模式

题目:编写简历,复制三份,做相应的修改

以下为深层复制

public class WorkExperience implements Cloneable {
    private String timeArea;
    private String company;

    public String getTimeArea() {
        return timeArea;
    }

    public void setTimeArea(String timeArea) {
        this.timeArea = timeArea;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    @Override
    protected Object clone() {
        Object o = null;
        try {
            o = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return o;
    }
}
public class Resume implements Cloneable {
    private String name;
    private String sex;
    private String age;
    private WorkExperience work;

    public Resume(String name) {
        this.name = name;
        work = new WorkExperience();
    }

    private Resume(WorkExperience work) {
        this.work = (WorkExperience) work.clone();
    }

    public void setPersonalInfo(String sex, String age) {
        this.sex = sex;
        this.age = age;
    }

    public void setWorkExperience(String timeArea, String company) {
        work.setTimeArea(timeArea);
        work.setCompany(company);
    }

    public void display() {
        System.out.println(name + "," + sex + "," + age);
        System.out.println("工作经历:" + work.getTimeArea() + "," + work.getCompany());
    }

    @Override
    protected Object clone() {
        Resume obj = new Resume(this.work);
        obj.name = this.name;
        obj.sex = this.sex;
        obj.age = this.age;
        return obj;
    }
}
public class Test {
    public static void main(String args[]) {
        Resume a = new Resume("小王");
        a.setPersonalInfo("男", "29");
        a.setWorkExperience("1999-2004", "XX公司");

        Resume b = (Resume) a.clone();
        b.setPersonalInfo("男", "25");

        Resume c = (Resume) a.clone();
        c.setWorkExperience("1995-2003", "YY公司");

        a.display();
        b.display();
        c.display();
    }
}

打印结果

小王,男,29
工作经历:1999-2004,XX公司
小王,男,25
工作经历:1999-2004,XX公司
小王,男,29
工作经历:1995-2003,YY公司

一般在初始化的信息不发生改变的情况下,克隆是最好的方法。这既隐藏了对象创建的细节,又对性能是大大的提高。

原文地址:https://www.cnblogs.com/anni-qianqian/p/7423869.html