原型模式(Prototype Pattern)
Specify the kinds of objects to create using a prototypicalinstance, and create new objects by copying this prototype.
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
类图:
从类图可以看到原型模式的核心方法是clone,在jdk中内置Cloneable接口,只需实现Cloneable接口即可实现原型类
代码如下
public class PrototypeClass implements Cloneable{
@Override
protected PrototypeClass clone() throws CloneNotSupportedException {
PrototypeClass prototypeClass=null;
try {
prototypeClass= (PrototypeClass) super.clone();
}catch (CloneNotSupportedException e){
e.printStackTrace();
}
return prototypeClass;
}
}
测试代码
public class Test {
public static void main(String[] args) {
try {
PrototypeClass prototypeClass=new PrototypeClass();
PrototypeClass prototypeClass1=prototypeClass.clone();
System.out.println(prototypeClass.equals(prototypeClass1));
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
输出
false
可以看到同过克隆方法产生了一个新的对象
此外还要注意深拷贝和前拷贝的区别
浅拷贝的对象如果包含引用或者是指针,当修个这个对象时,会引起原来对象的变化,这就非常危险,为了避免需要将包含的对象在堆中new 出来(即做深拷贝处理,相对比较简单)
参考 :百度百科