1.原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
2.结构图
3.原型模式其实就是从一个对象再创建另一个可定制的对象,而且不需知道任何创建的细节。
4.例子:复制简历
public class Resume implements Cloneable{
private String name ;
private String sex ;
private String age ;
private String timeArea ;
private String company ;
public Resume(String name){
this.name = name ;
}
//设置个人信息
public void SetPersonalInfo(String sex , String age){
this.sex = sex ;
this.age = age ;
}
//设置工作经历
public void SetWorkExperience(String timeArea , String company){
this.timeArea = timeArea ;
this.company = company ;
}
//打印
public void show(){
System.out.println(this.name + "," + this.age+"....");
}
//克隆
public Object Clone() throws CloneNotSupportedException{
return this.clone();
}
}
public class MainTest {
public static void main(String[] args) throws CloneNotSupportedException {
Resume a = new Resume("小明");
a.SetPersonalInfo("男", "22");
a.SetWorkExperience("1111", "ddd公司");
Resume b = (Resume)a.Clone();
b.SetPersonalInfo("女", "23");
System.out.println(a);
System.err.println(b);
}
}
用原来的方法时每new一次,都需要执行一次构造函数。如果构造函数执行时间很长,那么多次的执行这个初始化操作实在太低效。一般在初始化的信息不发生变化的情况下,克隆是最好的方法,这既能隐藏对象创建的细节,又对性能是大大的提高。
二.浅复制与深复制
1.如果字段是引用类型,则复制的只是对象的引用,因此原始对象及其副本引用同一个对象。
2.浅复制:被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象。
3.深复制:把引用对象的变量指向复制过的新对象,而不是原来的被引用对象。
4.例子 结构图:
//工作经历类
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;
}
public Object Clone() throws CloneNotSupportedException{
return this.clone();
}
}
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) {
try {
this.work = (WorkExperience)work.Clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
//设置个人信息
public void SetPersonalInfo(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 show(){
System.out.println(this.name + "," + this.age+"....");
}
//克隆
public Object Clone() throws CloneNotSupportedException{
Resume obj = new Resume(this.work);
obj.name = this.name;
obj.sex = this.sex ;
obj.age = this.age ;
return this.clone();
}
}
public class MainTest {
public static void main(String[] args) throws CloneNotSupportedException {
Resume a = new Resume("小明");
a.SetPersonalInfo("男", "22");
a.SetWorkExperience("1111", "ddd公司");
Resume b = (Resume)a.Clone();
b.SetPersonalInfo("女", "23");
System.out.println(a);
System.err.println(b);
}
}