設計模式----Prototype(原形)模式
GoF:用原型執行個體指定建立對象的種類,並且通過拷貝這些原型建立新的對象。
用過Java集合比如說,ArrayList、HashMap等的人都肯定有過將一個對象copy給另一個對象的經曆,其中clone ()方法可能都用過。Prototype模式就起到這樣的作用。Prototype模式允許一個對象再建立另一個對象,而根本無需知道任何如何建立的細節。(該處摘自板橋裡人-設計模式之Prototype(原型))這裡我們不討論深拷貝和淺拷貝的問題。(相關知識請參考《Thing in Java》附錄A那裡有詳細的解釋)
在Java中由於類Object提供了clone ()方法,來實現對象的複製。所以在Java中Prototype模式的實現變得非常簡單。
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 2006年3月28日, 下午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模式了。
在Java中Prototype模式幾乎變成了clone ()方法的調用。其實Java先天複雜的類庫給設計模式的實現提供了便利條件。比如Observer模式,Interator模式等。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=968297