原型模型經過拷貝建立對象,也可歸結爲的建立型的設計模式。設計模式
原型模式的示例:ide
public class Prototype { public static void main(String[] args) { Field field = new Field("code"); System.out.println("field=[" + field + "]"); field.setCode("codedes"); Field fieldCopy = field.clone(); System.out.println("fieldCopy=[" + fieldCopy + "]"); } } class Field implements Cloneable { private String code; public Field(String code) { this.code = code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "Field{" + "code='" + code + '\'' + '}'; } public Field clone() { Field field = null; try { field = (Field) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } return field; } }
一、實現Cloneable接口
二、調用object父類的clone方法進行拷貝。這裏的拷貝是淺拷貝。this
實現深拷貝:設計
public class Prototype { public static void main(String[] args) { Field field = new Field("code", new Type("string")); System.out.println("field=[" + field + "]"); field.setCode("codedes"); Field fieldCopy = field.clone(); System.out.println("fieldCopy=[" + fieldCopy + "]"); } } class Type implements Cloneable { private String typeName; public Type(String typeName) { this.typeName = typeName; } public Type clone(){ Type type = null; try { type = (Type) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return type; } } class Field implements Cloneable { private String code; private Type type; public Field(String code, Type type) { this.code = code; this.type = type; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "Field{" + "code='" + code + '\'' + ", type=" + type + '}'; } public Field clone() { Field field = null; try { field = (Field) super.clone(); field.type = type.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return field; } }
clone這種方式是先分配內存大小,而後經過內存塊的複製操做來實現賦值的,效率可能會比new出來一個對象的效率高點。code