原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。以下是例子:
//必须要实现 Cloneable ,调用clone()方法才不会抛出异常
public abstract class AbstractSpoon implements Cloneable{
String spoonName;
public void setSpoonName(String spoonName){
this.spoonName = spoonName; }
public String getSpoonName(){
return spoonName; }
public Object clone(){
Object object = null;
try{
object = super.clone(); }
catch(CloneNotSupportedException exception){
System.out.println("AbstractSpoon is not Cloneable"); }
return object; } }
public class SoupSpoon extends AbstractSpoon{
public SoupSpoon(){
this.setSpoonName("Soup Spoon"); } }
//测试类
public class Test {
public static void main(String[] args) {
AbstractSpoon ss = new SoupSpoon();
SoupSpoon sss = (SoupSpoon) ss.clone(); } }