用于建立重复的对象,同时又能保证性能。它属于建立型设计模式,它提供了一种建立对象的最佳方法。
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)想解耦框架与生成的实例时
想要让生成实例的框架不依赖于具体的类,这时,不能指定类名来生成实例,要事先”注册一个原型的“实例,而后经过复制该实例来生成新的实例。函数
待补充性能