原型模式(Prototype Pattern)
原型模式解决如下问题:
- 如何创建对象以支持在运行时指定哪一个对象被创建。
- 如何动态加载被实例化的类。
在一个类中直接创建所需要的对象是不灵活的,因为类在编译时指定特定对象,这样就不支持在运行时指定哪一个对象被创建。
原型模式提供如下解决办法:
- 定义一个原型对象返回它自身的拷贝。
- 通过拷贝一个原型对象创建新的对象。
用不同的原型对象配置一个类,用于拷贝创建新的对象,甚至于,原型对象能够动态地添加和删除。
创建一个实现了 Clonable 接口的抽象类。
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;
}
}
Java中任何实现了Cloneable接口的类都可以通过调用clone()方法来复制一份自身然后传给调用者。一般而言,clone()方法满足:
对任何的对象x,都有x.clone() !=x,即克隆对象与原对象不是同一个对象。
对任何的对象x,都有x.clone().getClass()==x.getClass(),即克隆对象与原对象的类型一样。
如果对象x的equals()方法定义恰当,那么x.clone().equals(x)应该成立。
创建扩展了上面抽象类的实体类。
Rectangle.java
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
PrototypePatternDemo.java
public class PrototypePatternDemo {
public static void main(String[] args) {
Shape shape = new Rectangle();
Shape clonedShape = shape.clone();
}
}