用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象,Prototype模式允许一个对象再创建另外一个可定制的对象,不需要知道任何如何创建的细节。Prototype的实现代码如下:
package yw.prototype;
public class AbstractSpoon implements Cloneable{
private String spoonName;
public String getSpoonName() {
return spoonName;
}
public void setSpoonName(String spoonName) {
this.spoonName = spoonName;
}
public Object clone(){
Object object=null;
try{
object=super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return object;
}
}
package yw.prototype;
public class SoupSpoon extends AbstractSpoon{
public SoupSpoon(){
setSpoonName("Soup Spoon");
}
}
//原型模式(Prototype)的调用代码
package yw.prototype;
public class App {
public static void main(String args[]){
SoupSpoon ss=new SoupSpoon();
SoupSpoon c=(SoupSpoon) ss.clone();
System.out.println(ss.getSpoonName());
System.out.println(c.getSpoonName());
}
}