前言
原型模式:根据原型实例创建新的克隆地址,克隆分为浅克隆和深克隆
浅克隆
先看如下代码:
这种是常见的浅克隆,仅仅只是将a的栈引用赋给了b
public class PrototypeVO{
private String age;
private String name;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
PrototypeVO a = new PrototypeVO();
PrototypeVO b = a;
System.out.println("a的地址:" + a.hashCode());
System.out.println("b的地址:"+b.hashCode());
}
打印结果:
a的地址:1433867275
b的地址:1433867275
深克隆
要想使用深克隆,则需要被克隆的对象实现Cloneable接口,并重写clone方法即可
public class PrototypeVO implements Cloneable{
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
然后我们用重写的clone方法再试试,可以发现堆地址已发生了变化。
public static void main(String[] args) throws CloneNotSupportedException {
PrototypeVO a = new PrototypeVO();
PrototypeVO b = (PrototypeVO) a.clone();
System.out.println("a的地址:" + a.hashCode());
System.out.println("b的地址:"+b.hashCode());
}
打印结果:
a的地址:1937962514
b的地址:274064559
但如果PrototypeVO里有其他对象需要进行深克隆,就需要额外一些工作量了
public class PrototypeVO implements Cloneable{
private HeaderVO headerVO;
public HeaderVO getHeaderVO() {
return headerVO;
}
public void setHeaderVO(HeaderVO headerVO) {
this.headerVO = headerVO;
}
/**
* 此为深克隆,浅克隆使用默认的return super.clone();即可
* 深克隆则需要将其下所有的实现类都重新克隆一份
* @return
* @throws CloneNotSupportedException
*/
@Override
protected Object clone() throws CloneNotSupportedException {
PrototypeVO newPrototypeVO = (PrototypeVO) super.clone();
if(newPrototypeVO.headerVO != null){
newPrototypeVO.headerVO = (HeaderVO) newPrototypeVO.headerVO.clone();
}
return newPrototypeVO;
}
}
public class HeaderVO implements Cloneable{
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}