直接可以理解为基于已有对象为原型,创建新的对象。适用于新对象和原对象差异较小,且对象创建过程耗时费力。
也就是复制,Java中可以通过实现Cloneable接口,由clone方法实现对象复制。当然也可以自己实现任何方式,只要能实现对象的复制即可。选择Cloneable是因为比 new 效率高。
而深浅克隆决定于clone方法的实现,也是原型模型的核心重点。默认是浅克隆,也就是说对于引用类型变量则是同一份。
以下代码演示了,生产不同的 T恤,直接可以clone并通过set方法快速修改样式,或颜色属性。
@AllArgsConstructor
@Data
public class Tshirt implements Cloneable {
private String size;
private String color;
private String material;
private String style;
private String logo;
protected Tshirt clone() throws CloneNotSupportedException {
return (Tshirt) super.clone();
}
public Tshirt setSize(String size) {
this.size = size;
return this;
}
public Tshirt setColor(String color) {
this.color = color;
return this;
}
public Tshirt setMaterial(String material) {
this.material = material;
return this;
}
public Tshirt setStyle(String style) {
this.style = style;
return this;
}
public Tshirt setLogo(String logo) {
this.logo = logo;
return this;
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Tshirt nike_vNeck_tshirt = new Tshirt("XXL","black","Cotton","V-neck","nike");
Tshirt nike_crewNeck_tshirt = nike_vNeck_tshirt.clone().setStyle("Crew-neck");
Tshirt nike_write_vNeck_tshirt = nike_vNeck_tshirt.clone().setColor("Write");
System.out.println(nike_vNeck_tshirt);
System.out.println(nike_crewNeck_tshirt);
System.out.println(nike_write_vNeck_tshirt);
}
}
Tshirt(size=XXL, color=black, material=Cotton, style=V-neck, logo=nike)
Tshirt(size=XXL, color=black, material=Cotton, style=Crew-neck, logo=nike)
Tshirt(size=XXL, color=Write, material=Cotton, style=V-neck, logo=nike)

1316

被折叠的 条评论
为什么被折叠?



