原型模式(Prototype)
在有些系统中,存在大量相同或相似对象的创建问题,如果用传统的构造函数来创建对象,会比较复杂且耗时耗资源,用原型模式生成对象就很高效,就像孙悟空拔下猴毛轻轻一吹就变出很多孙悟空一样简单。
原型模式的定义与特点
-
原型(Prototype)模式的定义如下:
用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。在这里,原型实例指定了要创建的对象的种类。用这种方式创建对象非常高效,根本无须知道对象创建的细节。 -
原型(Prototype)模式的优点:
1.性能提高。
2.逃避构造函数的约束。 -
原型(Prototype)模式的缺点:
1.配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
2.必须实现 Cloneable 接口。
原型模式的结构与实现
由于Java提供了对象的 clone() 方法,所以用 Java 实现原型模式很简单。
-
模式的结构
原型模式包含以下主要角色。- 抽象原型类:规定了具体原型对象必须实现的接口。
- 具体原型类:实现抽象原型类的 clone() 方法,它是可被复制的对象。
- 访问类:使用具体原型类中的 clone() 方法来复制新的对象。
其结构图如图 1 所示。
-
模式的实现
原型模式的克隆分为浅克隆和深克隆,Java 中的 Object 类提供了浅克隆的 clone() 方法,具体原型类只要实现 Cloneable 接口就可实现对象的浅克隆,这里的 Cloneable 接口就是抽象原型类。其代码如下:
//具体原型类
class Realizetype implements Cloneable
{
Realizetype()
{
System.out.println("具体原型创建成功!");
}
public Object clone() throws CloneNotSupportedException
{
System.out.println("具体原型复制成功!");
return (Realizetype)super.clone();
}
}
//原型模式的测试类
public class PrototypeTest
{
public static void main(String[] args)throws CloneNotSupportedException
{
Realizetype obj1=new Realizetype();
Realizetype obj2=(Realizetype)obj1.clone();
System.out.println("obj1==obj2?"+(obj1==obj2));
}
}
程序的运行结果如下:
具体原型创建成功!
具体原型复制成功!
obj1==obj2?false
原型模式的实例
我们将创建一个抽象类 Shape 和扩展了 Shape 类的实体类。下一步是定义类 ShapeCache,该类把 shape 对象存储在一个 Hashtable 中,并在请求的时候返回它们的克隆。PrototypePatternDemo,我们的演示类使用 ShapeCache 类来获取 Shape 对象。
1.创建一个实现了 Cloneable 接口的抽象类。Shape.java
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;
}
}
2.创建扩展了上面抽象类的实体类。Rectangle.java、Square.java、Circle.java
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.");
}
}
3.创建一个类,从数据库获取实体类,并把它们存储在一个 Hashtable 中。ShapeCache.java
import java.util.Hashtable;
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);
}
}
4.PrototypePatternDemo 使用 ShapeCache 类来获取存储在 Hashtable 中的形状的克隆。
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
原型模式的应用场景
- 对象之间相同或相似,即只是个别的几个属性不同的时候。
- 对象的创建过程比较麻烦,但复制比较简单的时候。
原型模式的扩展
原型模式可扩展为带原型管理器的原型模式,它在原型模式的基础上增加了一个原型管理器 PrototypeManager 类。该类用 HashMap 保存多个复制的原型,Client 类可以通过管理器的 get(String id) 方法从中获取复制的原型。其结构图如下图所示。
用带原型管理器的原型模式来生成包含“圆”和“正方形”等图形的原型,并计算其面积。分析:本实例中由于存在不同的图形类,例如,“圆”和“正方形”,它们计算面积的方法不一样,所以需要用一个原型管理器来管理它们,下图所示是其结构图。
程序代码如下:
import java.util.*;
interface Shape extends Cloneable
{
public Object clone(); //拷贝
public void countArea(); //计算面积
}
class Circle implements Shape
{
public Object clone()
{
Circle w=null;
try
{
w=(Circle)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println("拷贝圆失败!");
}
return w;
}
public void countArea()
{
int r=0;
System.out.print("这是一个圆,请输入圆的半径:");
Scanner input=new Scanner(System.in);
r=input.nextInt();
System.out.println("该圆的面积="+3.1415*r*r+"\n");
}
}
class Square implements Shape
{
public Object clone()
{
Square b=null;
try
{
b=(Square)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println("拷贝正方形失败!");
}
return b;
}
public void countArea()
{
int a=0;
System.out.print("这是一个正方形,请输入它的边长:");
Scanner input=new Scanner(System.in);
a=input.nextInt();
System.out.println("该正方形的面积="+a*a+"\n");
}
}
class ProtoTypeManager
{
private HashMap<String, Shape>ht=new HashMap<String,Shape>();
public ProtoTypeManager()
{
ht.put("Circle",new Circle());
ht.put("Square",new Square());
}
public void addshape(String key,Shape obj)
{
ht.put(key,obj);
}
public Shape getShape(String key)
{
Shape temp=ht.get(key);
return (Shape) temp.clone();
}
}
public class ProtoTypeShape
{
public static void main(String[] args)
{
ProtoTypeManager pm=new ProtoTypeManager();
Shape obj1=(Circle)pm.getShape("Circle");
obj1.countArea();
Shape obj2=(Shape)pm.getShape("Square");
obj2.countArea();
}
}
运行结果如下所示:
这是一个圆,请输入圆的半径:3
该圆的面积=28.2735
这是一个正方形,请输入它的边长:3
该正方形的面积=9