创建型模式:Prototype(原型)

WIKI:http://zh.wikipedia.org/wiki/%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F

原型模式创建型模式的一种,其特点在于通过「复制」一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的「原型」,这个原型是可定制的。

原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。

/** Prototype Class **/
public class Cookie implements Cloneable {
  
   public Object clone()
   {
       try{
           //In an actual implementation of this pattern you would now attach references to
           //the expensive to produce parts from the copies that are held inside the prototype.
           return this.getClass().newInstance();
       }
       catch(InstantiationException e)
       {
          e.printStackTrace();
          return null;
       }
   }
}

/** Concrete Prototypes to clone **/
public class CoconutCookie extends Cookie { }

/** Client Class**/
public class CookieMachine
{

  private Cookie cookie;//cookie必须是可复制的

    public CookieMachine(Cookie cookie) { 
        this.cookie = cookie; 
    } 
    public Cookie makeCookie() { 
      return (Cookie)cookie.clone(); 
    } 
    public Object clone() { } 

    public static void main(String args[]){ 
        Cookie tempCookie =  null; 
        Cookie prot = new CoconutCookie(); 
        CookieMachine cm = new CookieMachine(prot); //设置原型
        for(int i=0; i<100; i++) 
            tempCookie = cm.makeCookie();//通过复制原型返回多个cookie 
    } 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值