个人理解原型模式主要是深克隆浅克隆的问题,浅克隆只是实现Cloneable接口,重写clone方法return super.clone();即可,所以这里只重写了87页深克隆的代码:
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Resume a = new Resume("大鸟");
a.setPersonInfo("男", "29");
a.setWorkExperience("1998-2000", "XX公司");
Resume b = (Resume) a.clone();
b.setWorkExperience("1998-2006", "YY公司");
Resume c = (Resume) a.clone();
c.setPersonInfo("男", "24");
c.setWorkExperience("1998-2003", "ZZ公司");
a.display();
b.display();
c.display();
}
}
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) throws CloneNotSupportedException {
this.work = (WorkExperience) work.clone();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public WorkExperience getWork() {
return work;
}
public void setWork(WorkExperience work) {
this.work = work;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Resume obj = new Resume(this.work); //调用private构造方法
obj.name = this.name;
obj.sex = this.sex;
obj.age = this.age;
return obj;
}
//设置个人信息
public void setPersonInfo(String sex, String age) {
this.sex = sex;
this.age = age;
}
//设置工作经历
public void setWorkExperience(String workDate, String company) {
work.setWorkDate(workDate);
work.setCompany(company);
}
//显示
public void display() {
System.out.println(name + ", " + sex + ", " + age);
System.out.println("工作经历:" + work.getWorkDate() + ", " + work.getCompany());
}
}
public class WorkExperience implements Cloneable {
private String workDate;
private String company;
public String getWorkDate() {
return workDate;
}
public void setWorkDate(String workDate) {
this.workDate = workDate;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
运行结果