用於建立重複的對象,同時又能保證性能。它屬於建立型設計模式,它提供了一種建立對象的最佳方法。
Prototype (原型)
Product 角色負責定義用於複製現有實例來生成新實例的方法。在示例程序中,由 Product 接口扮演此角色。
ConcretePrototype(具體的原型)
ConcretePrototype 角色負責實現複製現有實例並生成新實例的方法。在示例程序中,由 MessageBox 類和 UnderlinePen 類扮演此角色。數據庫
Client(使用者)
Client 角色負責使用複製實例的方法生成新的實例。在示例程序中,由 Manager 類扮演此角色。設計模式
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; } }
//Rectangle public class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } //Square public class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } } //Circle public class Circle extends Shape { public Circle(){ type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
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); } }
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.println("Shape : " + clonedShape2.getType()); Shape clonedShape3 = (Shape) ShapeCache.getShape("3"); System.out.println("Shape : " + clonedShape3.getType()); } }
輸出結果以下:框架
Shape : Circle Shape : Square Shape : Rectangle
下文的適用場景其實也是它的優勢ide
(1)對象種類繁多,沒法將它們整合到一個類中時
(2)難以根據類生成實例時
生成實例的過程太過複雜,很難根據類來 生成實例,一般,在想生成一個和以前用戶經過操做所建立出來的實例徹底同樣的實例的時候,咱們會事先將用戶經過操做所建立出來的實例保存起來,而後在須要時經過複製來生成新的實例。
(3)想解耦框架與生成的實例時
想要讓生成實例的框架不依賴於具體的類,這時,不能指定類名來生成實例,要事先」註冊一個原型的「實例,而後經過複製該實例來生成新的實例。函數
待補充性能