一.小结
- 意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新对象。
- 特点:性能优良、逃避构造函数的约束(原型模式clone创建对象时构造函数不会执行);
必须实现 Cloneable 接口、对已有的类不一定容易实现。 - 使用场景:资源优化的场景、性能和安全要求的场景等。
- 注意事项:深拷贝与浅拷贝
- java中原型模式UML类图
二.例子
JDK中提供的CopyOnWriteArrayList,部分源码如下
public class CopyOnWriteArrayList<E> implements Cloneable {
/**
* Returns a shallow copy of this list. (The elements themselves
* are not copied.)
*
* @return a clone of this list
*/
public Object clone() {
try {
@SuppressWarnings("unchecked")
CopyOnWriteArrayList<E> clone =
(CopyOnWriteArrayList<E>) super.clone();
clone.resetLock();
// Unlike in readObject, here we cannot visibility-piggyback on the
// volatile write in setArray().
VarHandle.releaseFence();
return clone;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
}
三.推荐博客
https://www.cnblogs.com/betterboyz/p/9356190.html