原型模式是創(chuàng)建模式之一。
原型模式有助于創(chuàng)建具有更好性能的重復(fù)對象。
在原型模式中,將返回一個現(xiàn)有對象的克隆,而不是創(chuàng)建新的對象。
我們使用原型設(shè)計模式,如果創(chuàng)建一個新對象的成本是昂貴和資源密集型。
以下代碼顯示如何使用Prototype Pattern創(chuàng)建對象。
首先它創(chuàng)建一個Shape抽象類,實現(xiàn)Cloneable接口。
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; } }
然后它創(chuàng)建三個具體的類擴展Shape類。
class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } } class Circle extends Shape { public Circle(){ type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
之后,它創(chuàng)建一個ShapeProtoType類來返回形狀的原型。
class ShapeProtoType{ 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() { 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 Main{ public static void main(String[] args) { ShapeProtoType.loadCache(); Shape clonedShape = (Shape) ShapeProtoType.getShape("1"); System.out.println("Shape : " + clonedShape.getType()); Shape clonedShape2 = (Shape) ShapeProtoType.getShape("2"); System.out.println("Shape : " + clonedShape2.getType()); Shape clonedShape3 = (Shape) ShapeProtoType.getShape("3"); System.out.println("Shape : " + clonedShape3.getType()); } }
上面的代碼生成以下結(jié)果。
更多建議: