原型模式
用原型实例指定创建对象的种类,并且通过拷贝(克隆)这些原型创建新的对象。
结构图

代码
/**
* 原型类 可以设计为抽象类
*/
public class Resume implements Cloneable {
private String name;
private String education;
private Work work;
public Resume() {
}
public Resume(String name, String education, Work work) {
this.name = name;
this.education = education;
this.work = work;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public Work getWork() {
return work;
}
public void setWork(Work work) {
this.work = work;
}
@Override
public Object clone() {
Resume result = null;
try {
result = (Resume)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
result.work = (Work)(this.work.clone());
return result;
}
@Override
public String toString() {
return "我叫:" + this.name + " 学历:" + this.education + " " + this.work.toString();
}
}
/**
* 原型类中的属性
*/
public class Work implements Cloneable {
private String time;
private String name;
public Work(String time, String name) {
this.time = time;
this.name = name;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone(){
Work work = null;
try {
work = (Work) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return work;
}
@Override
public String toString() {
return this.time + " 时间段在 " + name + "工作";
}
}
/**
* 客户端类
*/
public class Main {
public static void main(String[] args) {
Work work = new Work("2012-2014","长江企业公司");
Resume r1 = new Resume("张三","本科", work);
Resume r2 = (Resume) r1.clone();
work.setName("黄河企业公司");
work.setTime("2014-2016");
Resume r3 = (Resume) r1.clone();
work.setName("秦淮河企业公司");
work.setTime("2016-2018");
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
}
}
输出结果

总结
通过原型模式,我们可以去少去很多创建对象的过程,隐藏了创建对象的过程,对性能大大的提升,在其中运用到的
clone()方法及为重要,克隆在Object中本身有克隆方法,一般是实现Cloneable接口来实现clone()方法,一般情
况下的克隆默认为浅拷贝(克隆)-如果类中字段类型是值类型,对该字段进行逐位复制,如果是引用类型,则复制引用
但是不复制引用对象,此情况下,原有对象和克隆出来的对象引用的是同一个对象。 而深拷贝(克隆)如果类中字段类
型是值类型,对该字段进行逐位复制,如果是引用类型,把引用对象的字段指向复制过来的新对象,而不是原来使用的对
象。