概览
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。
类图
实例
public class Prototype implements Cloneable{
@Override
protected Prototype clone() throws CloneNotSupportedException {
Prototype p=null;
try{
p=(Prototype)super.clone();
}catch (ClassCastException e){
e.printStackTrace();
}
return p;
}
}
public class ConcretePrototype extends Prototype{
private String field;
public ConcretePrototype(String filed){
this.field=filed;
}
@Override
public String toString() {
return field;
}
}
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Prototype obj1=new ConcretePrototype("abc");
Prototype obj2=obj1.clone();
Prototype obj3=obj1.clone();
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj3);
}
}
abc
abc
abc