原型模式(ProtoType)
通过一个原型对象来创建一个新对象(克隆)。Java中要给出Clonable接口的实现,具体类要实现这个接口,并给出clone()方法的实现细节,这就是简单原型模式的应用。
浅拷贝:只拷贝简单属性的值和对象属性的地址
深拷贝:拷贝本对象引用的对象,有可能会出现循环引用的情况。可以用串行化解决深拷贝。写到流里再读出来,这时会是一个对象的深拷贝结果。
import java.io.Serializable;
//工作经验类
public class WorkExperence implements Serializable{
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;
}
@Override
public String toString() {
return "WorkExperence [workDate=" + workDate + ", company=" + company
+ "]";
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
//简历类
public class Resume implements Cloneable,Serializable {
private String name;
private String age;
private String sex;
WorkExperence we;//工作经历对象
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Resume(String name) {
this.name = name;
we=new WorkExperence();
}
/**
*
* Set up the personal information
*
* @param age
* @param sex
*/
public void setSelfInfo(String age, String sex) {
this.age = age;
this.sex = sex;
}
/**
* Work experience in setting
*
* @param data
* @param company
*/
public void setWorkExperence(String data, String company) {
we.setWorkDate(data);
we.setCompany(company);
}
@Override
protected Object clone() throws CloneNotSupportedException {
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
out = new ObjectOutputStream(bo);
out.writeObject(this);
out.flush();
byte[] bs = bo.toByteArray();
ByteArrayInputStream bi = new ByteArrayInputStream(bs);
in = new ObjectInputStream(bi);
Object o = in.readObject();
return o;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public String toString() {
return "Resume [name=" + name + ", age=" + age + ", sex=" + sex
+ ", we=" + we + "]";
}
}
//main
public class ProtoType {
public static void main(String[] args) throws CloneNotSupportedException {
WorkExperence we=new WorkExperence();
Resume r1=new Resume("张三");
r1.setSelfInfo("21", "man");
r1.setWorkExperence("2014-12-12", "beijing");
System.out.println(r1.toString());
Resume r2=(Resume) r1.clone();
r2.setWorkExperence("2012-12-12", "changsha");
System.out.println(r2.toString());
}
}
打印结果:
注:一定要实现序列号接口,不然报错!