概括:原型模式就是对象对自己本身的一个复制,java中通过Object的clone方法实现,因为该方法的原理是内存中二进制流的处理,所以一种应用就是代替时间效率比较低的new方法,其次需要注意的问题就是复制过程中的深复制、浅复制问题。
通用类图:
通用代码:
抽象原型角色是Object?
package 通用;
public class PrototypeClass implements Cloneable {
private String str;
public void setStr(String str) {
this.str=str;
}
//可重写也可不重写?没有报错!
public PrototypeClass clone() {
PrototypeClass prototypeClass=null;
try {
prototypeClass=(PrototypeClass)super.clone();//这个地方为什么要定义为PrototypeClass类型;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototypeClass;
}
public void display() {
System.out.println(str);
}
}
场景类:
package 通用;
public class Client {
public static void main(String[] args) {
PrototypeClass pro=new PrototypeClass();
pro.setStr("abc");
pro.display();
PrototypeClass preCopy=pro.clone();
preCopy.display();
}
}
具体示例:
1、PPT简历复制:(课本考试例子一样,略,,,)
UML图:
代码实现:
package 简历;
public class WorkExperience implements Cloneable{
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;
}
public WorkExperience clone() {
WorkExperience work=null;
try {
work=(WorkExperience)super.clone();//注意super不要写成this;
//其次工作经历类的深复制不要忘记
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return work;
}
}
//具体原型角色
public class Resume implements Cloneable {
private String name;
private String sex;
private String age;
private WorkExperience work=null;
public Resume(String name) {
this.name=name;
work=new WorkExperience();
}
public void setPersonInfor(String sex,String age) {
this.age=age;
this.sex=sex;
}
public void setWorkExperience(String time,String company) {
work.setCompany(company);
work.setTime(time);
}
public void display() {
System.out.println(name+" "+age+" "+sex);
System.out.println("工作经历 : "+work.getCompany()+" "+work.getTime());
}
public Resume Clone() {
Resume r=null;
try {
r=(Resume) super.clone();
r.work=(WorkExperience)this.work.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return r;
}
}
//场景类
public class Client {
public static void main(String[] args) {
Resume a=new Resume("王二");
a.setPersonInfor("男", "20");
a.setWorkExperience("2018-2019", "google");
Resume b=a.Clone();
a.display();
b.display();
b.setWorkExperience("2016-2018", "baidu");
a.display();
b.display();
}
}
总结:
通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类型对象。
The end;
因篇幅问题不能全部显示,请点此查看更多更全内容