Java設計模式—原型模式
阿新 • • 發佈:2018-12-23
目錄
-
目的
原型模式屬於物件的建立模式。通過給出一個原型物件來指明所有建立的物件的型別,然後用複製這個原型物件的辦法創建出更多同類型的物件。即用原型例項指定建立物件的種類,並且通過拷貝這些原型建立新的物件。
-
應用例項
-
細胞的分裂
-
Java中Object 的 clone()方法
-
程式碼
原型角色:定義用於複製現有例項來生成新例項的方法;
package com.gary.pattern; public abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } //定義複製現有例項來生成新例項的方法 public Object clone(){ Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
具體實現角色:實現用於複製現有例項來生成新例項的方法
package com.gary.pattern; public class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } package com.gary.pattern; public class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } } package com.gary.pattern; public class Circle extends Shape { public Circle(){ type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
使用者角色:維護一個登錄檔,並提供一個找出正確例項原型的方法。最後,提供一個獲取新例項的方法,用來委託複製例項的方法生成新例項。
package com.gary.pattern; import java.util.Hashtable; public class ShapeCache { private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } /** * 對每種形狀都執行資料庫查詢,並建立該形狀 * shapeMap.put(shapeKey, shape); * 例如,我們要新增三種形狀 */ public static void loadCache() { Circle circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(),circle); Square square = new Square(); square.setId("2"); shapeMap.put(square.getId(),square); Rectangle rectangle = new Rectangle(); rectangle.setId("3"); shapeMap.put(rectangle.getId(),rectangle); } }
測試:
package com.gary.pattern;
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.printlna"Shape : " + clonedShape2.getType());
Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
System.out.println("Shape : " + clonedShape3.getType());
}
}
結果
Shape : Circle
Shape : Square
Shape : Rectangle
Process finished with exit code 0