下面的代码实现了原型的最本质功能,即克隆功能。为了完整,我特意加入了原型管理器。这段代码,大部分是来自程序员杂志2001期非鱼的一篇文章,我改正了其中的一些错误而导入到下面的代码之中。       另外,很多人喜欢用原型来实现工厂模式的功能或者结合工厂模式来使用。为了突出原形的本质功能,所以下面的代码并未加入这些东东。有兴趣的朋友,可以自己找相关的书来看。        好了,不多说了,代码说明一切,请看代码:
  /**  * Design Pattern In Java  * Name:Prototype  * 目的:利用Prototype创建一批同样的产品  * 原型:PrototypeRam  * 拷贝:ClonedRam  * P:Prototype  * C:Clone  * Author:blackphoenix  * Modify Date:2002-08-18   */   import java.util.*; /**  * 定义原型产品类 PrototypeRam  * 此类即后面用来产品大量产品的模板  */   
class PrototypeRam implements Cloneable {  String name;  public PrototypeRam() {   name="Hi,I am PrototypeRam!";  }  public Object clone() {   Object o=null;   try {    o=super.clone();   }   catch(CloneNotSupportedException e) {    System.err.println("PrototypeRam is not cloneable!");   }   return o;   } } 
/**  * 原型管理器,用来方便地对原型进行管理  * 可以实现自动注册原形的功能  * 由于原型管理器运行时只要一个实例,所以用单态实现它  */ 
class PrototypeManager {  private static PrototypeManager pm;  Hashtable prototypes=null;  private PrototypeManager() {   prototypes=new Hashtable();  }  public static PrototypeManager getManager() {   if(pm==null) {    pm=new PrototypeManager();   }   return pm;  }  public void register(String name,Object prototype) {   prototypes.put(name,prototype);  }  public void unregister(String name) {   prototypes.remove(name);  }  public Object getPrototype(String name) {   if(prototypes.containsKey(name)) {    return prototypes.get(name);   }else {    Object o=null;    try {     /**      * 自动查找原型管理器里不存在的类,并动态生成它      */     o=Class.forName(name).newInstance();     register(name,o);    }    catch(Exception e) {     System.err.println("Class "+name+"没有定义!");    }    return o;   }  }   } /**  * 客户端代码,使用PrototypeManager获得原型  * 通过PrototypeRam生成一批Ram  */ public class Prototype {  PrototypeManager pm=null;  public Prototype() {   pm=PrototypeManager.getManager();  }  public static void main(String[] args) {   String classname=null;   classname=args[0];   Prototype test=new Prototype();   PrototypeRam pRam=(PrototypeRam)(test.pm.getPrototype(classname));   if(pRam!=null) {      PrototypeRam[] cRam;    System.out.println("PrototypeRam:  "+pRam.name);    cRam=new PrototypeRam[10];    for(int i=0;i<10;i++) {     /**      * 生成一批克隆的Ram,并比较他们和原型的不同      */     cRam[i]=(PrototypeRam)pRam.clone();     System.out.println("Cloned Ram"+i+":   "+pRam.name);    }    }else {    System.err.println("Sorry,can't find the class!");   }     } 
} 
附:  代码经验正可以运行,输入 Java Prototype PrototypeRam即可得正确结果
   
 
  |