原型模式在JDK源码中有广泛的应用,想找原型模式的实现也比较容易,只要找Cloneable接口的子类即可。因为JDK源码中Cloneable的子类太多,本文只讨论最典型的几种。
ArrayList
首先看ArrayList和原型模式有关的代码:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
}
注意看注释写的是,clone()方法是一个浅拷贝,ArrayList中的元素并没有被拷贝,而是直接引用。其他的数据结构类比如HashMap、TreeMap、LinkedList等同理。
Calendar
首先看Calendar和原型模式有关的代码:
public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
/**
* Creates and returns a copy of this object.
*
* @return a copy of this object.
*/
@Override
public Object clone()
{
try {
Calendar other = (Calendar) super.clone();
other.fields = new int[FIELD_COUNT];
other.isSet = new boolean[FIELD_COUNT];
other.stamp = new int[FIELD_COUNT];
for (int i = 0; i < FIELD_COUNT; i++) {
other.fields[i] = fields[i];
other.stamp[i] = stamp[i];
other.isSet[i] = isSet[i];
}
other.zone = (TimeZone) zone.clone();
return other;
}
catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
}
与前边的数据结构类不同的是,Calendar的clone()方法给生成的新对象的成员变量传递的是旧对象的值的clone()产生的值,而不是引用,这是一种深拷贝。