定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新对象。
好处:新实例持有原实例的状态(各变量的值)
类型一:浅复制
代码:
package prototype_model.shallowcopy;
/**
* @author naivor
*原型模式-浅复制-场景类
*/
public class ShallowCopy {
public static void main(String [] args) {
Original originalA=new Original();
Original originalB=(Original) originalA.clone(); //originalB是复制originalA的引用而得到,持有originalA的状态
}
}
/**
*
* @author naivor
*原型模式-浅复制-克隆类
*/
class Original implements Cloneable{
private int a;
private String str;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
protected Object clone() {
Object object=null;
try{
object=(Object)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return object;
}
}
类型二:深复制
代码:
package prototype_model.deepcopy;
/**
* @author naivor 原型模式-深复制-场景类
*/
public class DeepCopy {
public static void main(String[] args) {
Original originalA = new Original();
Original originalB = (Original) originalA.clone(); // originalB是复制originalA的变量值而得到,持有originalA的状态
}
}
/**
*
* @author naivor 原型模式-深复制-克隆类
*/
class Original implements Cloneable {
private int a;
private String str;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
protected Object clone() {
Original object = new Original();
object.a = this.a;
object.str = this.str;
return object;
}
}