定义:用一个已经创建的实例对象作为原型,通过复制该原型对象来创建一个和原型对象相同或相似的新对象。避免了重复执行耗时耗资源的new构造函数过程
优点:
缺点:
应用场景:
结构:
浅克隆和深克隆:
示例如下:
public class PrototypeTest {
public static void main(String[] args) {
Prototype prototype1 = new Prototype("zhang_san", new DeepClone());
Prototype prototype2 = (Prototype) prototype1.clone();
System.out.println("prototype1和prototype2的内存地址是否一样:" + (prototype1 == prototype2));
prototype2.setName("li_si");
}
}
// 用于实现深克隆
class DeepClone implements Cloneable {
public DeepClone() {
}
public Object clone() {
DeepClone deepClone = null;
try {
deepClone = (DeepClone) super.clone();
} catch (CloneNotSupportedException e) {
}
return deepClone;
}
}
// 具体原型类
class Prototype implements Cloneable {
private String name;
private DeepClone deepClone;
public Prototype(String name, DeepClone deepClone) {
this.name = name;
this.deepClone = deepClone;
System.out.println("原型对象创建成功");
}
public String getName() {
return this.name;
}
// 用于对复制的新对象修改属性。实现相似对象的复制功能
public void setName(String name) {
this.name = name;
}
public DeepClone getDeepClone() {
return this.deepClone;
}
public void setDeepClone(DeepClone deepClone) {
this.deepClone = deepClone;
}
public Object clone() {
Prototype prototype = null;
try {
// 实现浅克隆
prototype = (Prototype) super.clone();
// 实现深克隆
prototype.deepClone = (DeepClone) prototype.deepClone.clone();
} catch (CloneNotSupportedException e) {
System.out.println("原型对象复制失败");
}
System.out.println("原型对象复制成功");
return prototype;
}
}
运行程序,结果如下:
原型对象创建成功
原型对象复制成功
prototype1和prototype2的内存地址是否一样:false