抽象的父类通过实现Cloneable接口,继而重写接口中的clone方法,然后让各个实体类继承此父类,之后再建立一个拥有获取实体类的克隆体的方法的类,通过第一次new对象之后,再创建对对象的时候就不用再new了,而是将之前的对象克隆即可,这样省去了new对象的步骤,在运行阶段才能确定实例的时候使用这种设计模式。
网络上的专业解释: 这种模式实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回他的克隆,在需要的时候更新数据库,以次来减少数据库的调用。
实例:用原型模式完成对多个圆形和矩形的创建:
1)抽象父类的创建(必实现Cloneable接口)
public abstract class Shape implements Cloneable {
private String id;
protected String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
abstract void draw();
@Override
protected Object clone(){
Object clone=null;
try {
clone=super.clone();
System.out.println("cloned");
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clone;
}
}
2)实体类创建
public class Circle extends Shape{
public Circle() {
type="circle";
}
@Override
void draw() {
System.out.println("Circle draw()");
}
}
public class Rectangle extends Shape {
public Rectangle() {
type="rectangle";
}
@Override
void draw() {
System.out.println("Rectangle draw()");
}
}
3)获取实体的克隆类
public class ShapeCache {
private static Hashtable shapeMap=new Hashtable();
public static Shape getShape(String shapeId){
Shape cacheShape=shapeMap.get(shapeId);
return (Shape) cacheShape.clone();
}
//添加形状
public static void loadCache(){
Circle circle=new Circle();
circle.setId("1");
shapeMap.put(circle.getId(), circle);
Rectangle rectangle=new Rectangle();
rectangle.setId("2");
shapeMap.put(rectangle.getId(), rectangle);
}
}
4)测试类
public class PrototypeTest {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape cloneShape,cloneShape1;
for(int i=0;i<3;i++){
cloneShape=ShapeCache.getShape("1");
System.out.println("Shape 1 :"+cloneShape.getType());
cloneShape.draw();
cloneShape1=ShapeCache.getShape("2");
System.out.println("Shape 2 :"+cloneShape1.getType());
cloneShape1.draw();
}
}
}
5)后台运行
cloned
Shape 1 :circle
Circle draw()
cloned
Shape 2 :rectangle
Rectangle draw()
cloned
Shape 1 :circle
Circle draw()
cloned
Shape 2 :rectangle
Rectangle draw()
cloned
Shape 1 :circle
Circle draw()
cloned
Shape 2 :rectangle
Rectangle draw()