设计模式原型模式
本文最后更新于:2024年3月18日 凌晨
设计模式原型模式
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
实例
我们将创建一个抽象类 Shape 和扩展了 Shape 类的实体类。下一步是定义类 ShapeCache ,该类把 shape 对象存储在一个 Hashtable 中,并在请求的时候返回它们的克隆。
PrototypePatternDemo 类使用 ShapeCache 类来获取 Shape 对象。
步骤 1
创建一个实现了 Cloneable 接口的抽象类,并创建扩展了上面抽象类的实体类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 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." ); } }public class Square extends Shape { public Square () { type = "Square" ; } @Override public void draw () { System.out.println("Inside Square::draw() method." ); } }public class Circle extends Shape { public Circle () { type = "Circle" ; } @Override public void draw () { System.out.println("Inside Circle::draw() method." ); } }
步骤 2
创建一个类,从数据库获取实体类,并把它们存储在一个 Hashtable 中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 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 () { 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); } }
步骤 3
PrototypePatternDemo 使用 ShapeCache 类来获取存储在 Hashtable 中的形状的克隆。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 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()); } }
1 2 3 Shape : Circle Shape : Square Shape : Rectangle