Java原型模式,
分享于 点击 4446 次 点评:53
Java原型模式,
设计模式复习,代码是最好的说明。
定义:用原型实例指定创建类的种类,并通过拷贝这些原型创建新的对象,属于创建类模式。
UML:略
原型模式主要用于对象的复制,优点是:提升性能和简化创建对象过程。它需要满足两个条件:实现cloneable接口和重写clone方法。有两种拷贝方式:浅拷贝和深拷贝,区别在于浅拷贝只拷贝基本数据类型,其余为引用。
代码:
浅拷贝:
class Prototype implements Cloneable{
/**
* 修改protected->public Object->Prototype
* @return
* @throws CloneNotSupportedException
*/
// @Override
// protected Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
@Override
public Prototype clone() throws CloneNotSupportedException {
Prototype prototype = (Prototype) super.clone();
return prototype;
}
}
深拷贝:
class Prototype implements Cloneable{
private ArrayList arrayList;
/**
* 修改protected->public Object->Prototype 拷贝内部对象引用
* @return
* @throws CloneNotSupportedException
*/
// @Override
// protected Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
@Override
public Prototype clone() throws CloneNotSupportedException {
Prototype prototype = (Prototype) super.clone();
prototype.arrayList = (ArrayList) arrayList.clone();
return prototype;
}
}
原型模式一般不单独使用,我在这篇文章中有使用http://blog.csdn.net/poyuan97/article/details/78070136
如有错误,欢迎指出!
相关文章
- 暂无相关文章
用户点评