《Java與模式》學習筆記之八—原始模型模式(Prototype Pattern)

來源:互聯網
上載者:User

    原始模型模式屬於對象的建立模式,通過給出一個原型對象來指明所要建立的對象的類型,然後用複製這個原型對象的辦法建立出更多同類型的對象。

    原始模型模式有兩種形式:簡單形式和登記形式。

    簡單形式的原始模型類圖:

   

原始碼:

public interface Prototype extends Cloneable {

    Object clone();

}

 

public class ConcretePrototype implements Prototype {

    public Object clone()

    {

           System.out.println("return new ConcretePrototype()");

        return new ConcretePrototype();

    }

}

 

public class Client {

       public static void main(String[] args) {

              Prototype thePrototype = new ConcretePrototype();

              Prototype pt1 = (Prototype)thePrototype.clone();

       }

}

登記形式的原始模型模式類圖:

其中:

原型管理器(PrototypeManager)角色:建立具體原型類的對象,並記錄每一個被建立的對象。

原始碼:

public interface Prototype extends Cloneable {

       Object clone();

}

 

public class ConcretePrototype implements Prototype {

       public Object clone()

       {

              return new ConcretePrototype();

       }

}

 

public class PrototypeManager {

    private Vector arrPrototype = new Vector();

    public void addPrototype(Prototype pt)

    {

           arrPrototype.add(pt);

    }

   

    public Prototype getPrototype(int index)

    {

           return (Prototype)arrPrototype.get(index);

    }

   

    public int getSize()

    {

           return arrPrototype.size();

    }

}

 

public class Client {

       public static void main(String[] args) {

              PrototypeManager mgr = new PrototypeManager();

              Prototype thePrototype = new ConcretePrototype();

              Prototype pt1 = (Prototype)thePrototype.clone();

              Prototype pt2 = (Prototype)thePrototype.clone();

              mgr.addPrototype(pt1);

              mgr.addPrototype(pt2);

              System.out.println("" + mgr.getSize());

       }

}

兩種形式的比較:

如果需要建立的原型對象數目較少而且比較固定,用簡單形式的原始原型模式;如果要建立的原型對象數目不固定,用登記形式的原始模型模式。

三種常用建立型模式的比較:

    Builder模式重在複雜物件的一步步建立(並不直接返回對象),AbstractFactory模式重在產生多個相互依賴類的對象,而Prototype模式重在從自身複製自己建立新類。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.