原型模式
1基本概念:
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
优点:
1、性能提高。
2、逃避构造函数的约束。
缺点:
1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
2、必须实现 Cloneable 接口。
代码样例:
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;
}
//重写clone方法
public Object Clone(){
Object clone = null;
try{
clone = super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return clone;
}
}
//抽象类的实体类
public class Rectangle extends Shape{
public Rectangle(){
type = “Rectangle”;
}
public void draw(){
System.out.println(“Rectangle”);
}
}
public class Square extends Shape{
public Square (){
type = "Square ";
}
public void draw(){
System.out.println("Square ");
}
}
public class Circle extends Shape{
public Circle (){
type = "Circle ";
}
public void draw(){
System.out.println("Circle ");
}
}
//用一个类模拟从数据库取出实体类放入hashtable
public class ShapeCache{
//用hashtable来存放实体对象
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();
}
//对于每种形状都创建
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);
Square square = new Square ();
square .setId("3");
shapeMap.put(square .getId(),square );
}
}
public class ProtoTypeDemo{
public static void main(String args[]){
ShapeCache.loadCache();
Shape clonedShape = (Shape)ShapeCache.getShape(“1”);
System.out.println(“shape:”+cloneShape.getType());
Shape clonedShape = (Shape)ShapeCache.getShape(“2”);
System.out.println(“shape:”+cloneShape.getType());
Shape clonedShape = (Shape)ShapeCache.getShape(“3”);
System.out.println(“shape:”+cloneShape.getType());
/*输出结果:
Shape:Circle
Shape:Rectangle
Shape:Square
*/
}
}