设计模式之原型模式

前言

原型模式(Prototype Pattern),核心思想是用原型实例复制出新实例对象,在java中通过Object中的clone方法进行对象的复制,当我们需要类实例可复制时,该类要实现Cloneable标志性接口,用于标明该类实例是可复制的,否则,当我们调用该类实例的clone方法时,会抛出CloneNotSupportedException异常。

深拷贝与浅拷贝

对于引用类型的变量,深拷贝是对变量所指向实例的完全拷贝,而浅拷贝则只是对该变量引用地址进行拷贝。其中Object中的clone方法,只是进行对象的浅拷贝,如果需要对象的深拷贝,要重写clone方法。

/**
* 功能描述:基础信息
*/
public class BasicInfo implements Cloneable {
/**姓名*/
private String name = null;
/**年龄*/
private int age;
/**手机号*/
private String phoneNo = null;
/**家庭地址*/
private String address = null;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getPhoneNo() {
return phoneNo;
}

public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public BasicInfo clone() {
try{
BasicInfo info = (BasicInfo) super.clone();
return info;
}catch(CloneNotSupportedException e){
System.err.println(e);
}
return null;
}

}

/**
* 功能描述:学生类
*/
public class Student implements Cloneable {
/**学号*/
private String number = null;
/**院系*/
private String department = null;
/**专业*/
private String profession = null;
/**引用类型:学生基础信息*/
private BasicInfo info = null;

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

public String getProfession() {
return profession;
}

public void setProfession(String profession) {
this.profession = profession;
}

public BasicInfo getInfo() {
return info;
}

public void setInfo(BasicInfo info) {
this.info = info;
}

}

浅拷贝示例:

@Override
public Student clone() {
try{
Student sc = (Student) super.clone();
return sc;
}catch(CloneNotSupportedException e){
System.err.println(e);
}
return null;
}

深拷贝示例:

@Override
public Student clone() {
try{
Student sc = (Student) super.clone();
BasicInfo cInfo = info.clone();
sc.setInfo(cInfo);
return sc;
}catch(CloneNotSupportedException e){
System.err.println(e);
}
return null;
}

总结

实现一个对象的深拷贝,除了重写Object中的protected clone()方法外,也可以通过java的序列化与反序列化机制实现深拷贝,但是在性能上来说,clone方法的性能要高于序列化与反序列化方式。