设计模式----Prototype(原形)模式

来源:互联网 发布:vwap算法 编辑:程序博客网 时间:2024/05/01 06:18

设计模式----Prototype(原形)模式

 

GoF用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

 

用过Java集合比如说,ArrayListHashMap等的人都肯定有过将一个对象copy给另一个对象的经历,其中clone ()方法可能都用过。Prototype模式就起到这样的作用。Prototype模式允许一个对象再创建另一个对象,而根本无需知道任何如何创建的细节。(该处摘自板桥里人-设计模式之Prototype(原型))这里我们不讨论深拷贝和浅拷贝的问题。(相关知识请参考《Thing in Java》附录A那里有详细的解释)

 

Java中由于类Object提供了clone ()方法,来实现对象的克隆。所以在JavaPrototype模式的实现变得非常简单。

 

Prototype模式,其实也是非常简单的模式之一。我们通过一个实例来展现Prototype模式:

package Prototype;

 

public abstract class AbstractMobile implements Cloneable

{

    String mobileName;

   

    public void setMobileName(String name)

    {

        mobileName = name;

    }//end setMobileName(...)

   

    public String getMobileName()

    {

        return mobileName;

    }//end getMobileName()

   

    public Object clone()//实现clone方法

    {

        Object object = null;

        try{

            object = super.clone();

        }catch(CloneNotSupportedException cloneException){

            System.err.println("AbstratMobile is not Cloneable");

            cloneException.printStackTrace();

        }

        return object;

    }//end clone()

   

}//end abstract class AbstractMobile

 

package Prototype;

 

public class Mobile extends AbstractMobile

{

   

    /** Creates a new instance of Mobile */

    public Mobile()

    {

      //  super.setMobileName("NOKIA");

    }//end Mobile

  

}//end class Mobile

 

Prototype模式的调用:

/*

 * PrototypePattern.java

 *

 * Created on 2006328, 下午11:56

 *

 * To change this template, choose Tools | Template Manager

 * and open the template in the editor.

 */

 

package Prototype;

 

public class PrototypePattern

{

    AbstractMobile mobile = new Mobile();

    AbstractMobile newMobile = (Mobile)mobile.clone();//返回的是Object这里需要类型转换

 

    public void showPrototypePattern()

    {

        mobile.setMobileName("NOKIA");

        String mobileType = mobile.getMobileName();

        System.out.println("The new mobile is " + mobileType);

    }//end showPrototypePattern()

   

    public static void main(String[] args)

    {

        System.out.println("The Prototype Pattern!");

        PrototypePattern pp = new PrototypePattern();

        pp.showPrototypePattern();

    }//end main(...)

   

}//class PrototypePattern

 

下面是UML图,这里的图比较简单。但是已经能够反映出Prototype模式了。

 

 

JavaPrototype模式几乎变成了clone ()方法的调用。其实Java先天复杂的类库给设计模式的实现提供了便利条件。比如Observer模式,Interator模式等。

 

 

 

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=968297