原型模式
概述
不通过 new 关键字来产生一个对象, 而是通过对象复制来实现的模式就叫做原型模式. 这种主要是在 new 一个对象开销太大(相比于复制), 而需要大量的对象的情况下.
实现
首先要继承 Cloneable 接口, 实现其 clone()方法, 然后
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public abstract class Shape implements Cloneable {
private String id;
abstract void draw();
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;
}
}
实现具体类
1
2
3
4
5
6
7
8
9
10
11
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
假设下文的 getShapeById 是个耗时很大的操作(即使耗时不大, 一般也是复制比new快), 那么我们可以在查询一次后, 通过复制来构建大量的对象.
1
2
Shape shape = cachedShape.getShapeById("1");
Shape newShapeObj = shape.clone();