定义:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.
Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
结构图:
public class Resume implements Cloneable{
private String name;
private String sex;
private int age;
private WorkExperience workExperience;
public Resume(String name){
this.name = name;
workExperience = new WorkExperience();
}
//提供Clone方法调用的私有构造函数,以便克隆“工作经历”的数据
private Resume(WorkExperience work){
this.workExperience = (WorkExperience) work.clone();
}
public void SetPersonalInfo(String sex, int age) {
this.sex = sex;
this.age = age;
}
public void SetWorkExperience(String time,String company){
workExperience.setCompany(company);
workExperience.setTime(time);
}
public void Show(){
System.out.println(name + " " + sex + " " + age);
System.out.println("工作经验 " + workExperience.getTime()+ " " + workExperience.getCompany());
}
public Object clone(){
/*
Object prototype = null;
try{
prototype = (Object)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return prototype;
*/
Resume obj = new Resume(this.workExperience);
obj.name = this.name;
obj.age = this.age;
obj.sex = this.sex;
return obj;
}
}
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 Object clone(){
Object proprety = null;
try {
proprety = super.clone();
} catch (Exception e) {
e.printStackTrace();
}
return proprety;
}
}
public class Client {
public static void main(String[] args) {
Resume resume = new Resume("大鸟");
resume.SetPersonalInfo("男", 22);
resume.SetWorkExperience("1994-3-4", "ABC");
Resume resume2 =(Resume) resume.clone();
resume2.SetWorkExperience("1994-3-4", "aaaABC");
Resume resume3 =(Resume) resume.clone();
resume3.SetWorkExperience("1994-3-4222", "aABC");
//浅克隆
resume.Show();
resume2.Show();
resume3.Show();
}
}
. 适用性
原型模式的主要思想是基于现有的对象克隆一个新的对象出来,一般是有对象的内部提供克隆的方法,通过该方法返回一个对象的副本,这种创建对象的方式,相比我们之前说的几类创建型模式还是有区别的,之前的讲述的工厂模式与抽象工厂都是通过工厂封装具体的new操作的过程,返回一个新的对象,有的时候我们通过这样的创建工厂创建对象不值得,特别是以下的几个场景的时候,可能使用原型模式更简单也效率更高。
• 1)当一个系统应该独立于它的产品创建、构成和表示时,要使用 Prototype模式
• 2)当要实例化的类是在运行时刻指定时,例如,通过动态装载;
• 3)为了避免创建一个与产品类层次平行的工厂类层次时
• 4)当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。(也就是当我们在处理一些对象比较简单,并且对象之间的区别很小,可能只是很固定的几个属性不同的时候,可能我们使用原型模式更合适)。