原型模式定義:
用原型實例指定建立對象的種類,而且經過拷貝這些原型建立新的對象.java
Prototype模式容許一個對象再建立另一個可定製的對象,根本無需知道任何如何建立的細節,工做原理是:經過將一個原型對象傳給那個要發動建立的對象,這個要發動建立的對象經過請求原型對象拷貝它們本身來實施建立。c#
如何使用?
由於Java中的提供clone()方法來實現對象的克隆,因此Prototype模式實現一會兒變得很簡單.測試
import java.util.Hashtable; public class SymbolLoader { private Hashtable symbols = new Hashtable(); public SymbolLoader() { symbols.put("Line", new LineSymbol()); symbols.put("Note", new NoteSymbol()); } public Hashtable getSymbols() { return symbols; } }
public class LineSymbol extends Graphic { public LineSymbol() { } public void DoSomething() { System.out.println("I am used to draw a line !"); } }
public class NoteSymbol extends Graphic { public NoteSymbol() { } public void DoSomething() { System.out.println("I am used to draw a note !"); } }
public interface IGraphic extends Cloneable, Serializable { public String getName() ; public void setName(String gName); }
public abstract class Graphic implements IGraphic { private String name; public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e){ System.out.println("Do not support clone !!!"); throw new InternalError(); } } /* (non-Javadoc) * @see corner.dp.create.Prototype.mypackage.IGraphic#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see corner.dp.create.Prototype.mypackage.IGraphic#setName(java.lang.String) */ public void setName(String gName) { name = gName; } public abstract void DoSomething(); }測試代碼:
public class GraphicTool { public static void main(String[] args) { //----- Initial our prototype instance ---------- SymbolLoader myLoader = new SymbolLoader(); Hashtable mySymbols = myLoader.getSymbols(); //----- Draw a Line ------------------------------- Graphic myLine = (Graphic)((Graphic)mySymbols.get("Line")).clone(); myLine.DoSomething(); } }