原型模型通过拷贝创建对象,也可归结为的创建型的设计模式。
原型模式的示例:
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;
}
}
1、实现Cloneable接口
2、调用object父类的clone方法进行拷贝。这里的拷贝是浅拷贝。
实现深拷贝:
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出来一个对象的效率高点。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。