什么是原型模式?
原型模式是一种创建行为模式,和建造者相似,都是为创建对象而存在的设计模式。
什么时候应用原型模式?
原型模式的设计初衷是为了高性能的拷贝对象,如果一个对象在初始化的过程中需要很多准备,很高的资源消耗的时候,第二次使用这个对象的时候还得再重复一遍,使用原型模式,可以直接对该对象进行克隆。高效。
如何实现原型模式?
实现原型模式的关键是实现克隆操作,在 JAVA 继承 Cloneable,重写 clone()方法。
原型模式有什么缺点呢?
1,必须继承Cloneable 实现其中的clone()方法。
2,忽略了构造方法
3,配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候
public abstract class Shape implements Cloneable{
public String id;
public String type;
abstract void draw();
//getter and setter 省略
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
定义待拷贝对象Circle
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
定义待拷贝对象Rectangle
public class Rectangle extends Shape {
public Rectangle() {
type = "Rectangle";
}
@Override
void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
定义待拷贝对象Square
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
放在缓存ShapeCache中待使用:
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();
}
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);
}
}
测试Client
public class Client {
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());
}
}
整个代码的关键在方法
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
中,注意的是这里获取了缓存中的对象cachedShape之后没有直接返回该对象,而是返回的是对象的克隆对象。