当你需要一个对象的原型的时候(复制),这时候你可以会需要用到原型模式
一、在去公司面试的时候,你肯定需要简历,你可能会把一份简历复印多份,用代码描述下简历复印的过程
简历类:
public class Resume{
private String name;
private String sex;
private WorkTime workTime;
public Resume() {
workTime=new WorkTime();
}
private Resume(WorkTime workTime) throws CloneNotSupportedException {
this.workTime=(WorkTime) workTime.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 void setTime(String time) {
this.workTime.setTime(time);
}
public String getTime() {
return this.workTime.getTime();
}
public void setCompany(String company) {
this.workTime.setCompany(company);
}
public String getCompany(String company) {
return this.workTime.getCompany();
}
@Override
protected Object clone() throws CloneNotSupportedException {
Resume resume=new Resume(this.workTime);
resume.setName(this.name);
resume.setSex(this.sex);
return resume;
}
public void display() {
System.out.println("姓名:"+ this.name);
System.out.println("性别:"+this.sex);
System.out.println("在"+this.workTime.getCompany()+"工作"+this.workTime.getTime());
}
}
WorkTime类
public class WorkTime {
private String time;
private String company;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
protected Object clone() throws CloneNotSupportedException {
WorkTime workTime=new WorkTime();
workTime.setCompany(this.company);
workTime.setTime(this.time);
return workTime;
}
}
测试类:
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Resume resume=new Resume();
resume.setName("小明");
resume.setSex("男");
resume.setTime("2年");
resume.setCompany("xx");
Resume resumeClone=(Resume) resume.clone();
resumeClone.setName("小王");
resumeClone.setCompany("餐馆");
resume.display();
resumeClone.display();
}
}
输出结果:
这里涉及到一个比较重要的点就是深拷贝和浅拷贝的问题,如果父类里面含有对象的引用,那么如果不是用深拷贝的话,当修改小王的workTime时候,就也会修改小明的。所以均需要重写clone方法,重新生成一个对象