設計模式之原型模式——Java語言描述
阿新 • • 發佈:2019-01-05
原型模式是用於建立重複物件,同時又能保證效能。這種型別的設計模式屬於建立型模式,它提供了一種建立物件的方式
這種模式實現了一個原型介面,該介面用於建立當前物件的克隆。當直接建立物件的代價比較大時,則適合採用這種模式。
應用例項:
- 細胞分裂
- Java中的Object.clone()方法
優點:
- 效能較高
- 逃避建構函式的約束
缺點:
- 配備克隆方法需要對類的功能進行通盤考慮,這對於全新的類不是很難,但對於已有的類不一定很容易,特別當一個類引用不支援序列化的間接物件,或者引用含有迴圈結構的時候。
- 必須實現 Cloneable 介面。
實現
我們將建立一個抽象類Shape並且擴充套件了Shape類的實體類。下一步是定義類 ShapeCache,該類把shape物件儲存在一個Hashtable中,並在請求的時候返回它們的克隆。
Shape抽象類
public abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); public String getType(){ return type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
拓展實體類
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
建立實體快取
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(); } // 對每種形狀都執行資料庫查詢,並建立該形狀 public static void loadCache() { Rectangle rectangle = new Rectangle(); rectangle.setId("1"); shapeMap.put(rectangle.getId(),rectangle); } }
演示使用:
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
}
}
輸出結果:
Shape : Rectangle