一、定义
原型模式属于对象创建模式, GOF 给它的定义为:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
在 Java 中提供了 clone()方法来实现对象的克隆,所以 Prototype 模式实现变得简单许多。 注: clone()方法的使用,请参考《Thinking in Java》或者《Effective Java》,对于许多原型模式中讲到的浅克隆、深克隆,本文不作为谈论话题
二、何时使用
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
三、实例
package Prototype; public class Shape implements Cloneable{ private int id; protected String type; public Object clone(){ Object obj = null; try { obj = super.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } } class Circle extends Shape{ public Circle(){ type = "circle"; } public void show(){ System.out.println("circle"); } } class Square extends Shape{ public Square(){ type = "Square"; } public void show(){ System.out.println("Square"); } } class Rectangle extends Shape{ public Rectangle(){ type = "Rectangle"; } public void show(){ System.out.println("Rectangle"); } }
package Prototype; import java.util.Hashtable; public class Shapecache { public static Hashtable<Integer,Shape> cachemap = new Hashtable<Integer,Shape>(); public Shape getshape(int id){ return (Shape) cachemap.get(id).clone(); } public void cacheinit(){ Circle c = new Circle(); c.setId(1); cachemap.put(1, c); Square s = new Square(); s.setId(2); cachemap.put(2, s); Rectangle r = new Rectangle(); r.setId(3); cachemap.put(3, r); } }
package Prototype; public class Client { public static void main(String[] args){ Shapecache sc = new Shapecache(); sc.cacheinit(); Shape shape1 = sc.getshape(1); System.out.println(shape1.getType()+" "+shape1.getId()); Shape shape2 = sc.getshape(2); System.out.println(shape2.getType()+" "+shape2.getId()); Shape shape3 = sc.getshape(3); System.out.println(shape3.getType()+" "+shape3.getId()); } }
//输出结果: circle 1 Square 2 Rectangle 3
这里面有4个角色:
- 抽象原型角色:实现了自己的 clone 方法,扮演这种角色的类通常是抽象类,且它具有许多具体的子类。
- 具体原型角色:被复制的对象,为抽象原型角色的具体子类。
- 缓存器: 让一个原型克隆自己来得到一个新对象。
- 客户角色:调用缓存器。