8.原型模式(Prototype)

Posted by Jfson on 2018-06-22

通过克隆基于现有对象创建对象(克隆羊)
当需要一个与现有对象类似的对象时,或者与克隆相比,创建的成本会很高。

示例:Arraylist的clone()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ArrayList<Student> listCopy=(ArrayList<Student>) list.clone();
public Object clone() {
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) 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();
}
}


pv UV: