原型模式就是指clone对象。当我们要克隆一个对象,这个对象需要实现Cloneable接口,并重写object的clone()方法。克隆分为浅克隆和深克隆。针对一个对象中有引用对象的话,引用对象是否克隆,决定了浅克隆还是深克隆。浅克隆只是clone了引用,具体引用指向的对象都是一个。 深克隆的话不仅是克隆的引用,引用所指向的对象也是克隆的。
/**
* 浅克隆
*/
public class MainPrototype {
public static void main(String[] args) throws CloneNotSupportedException {
Product p1 = new Product("面包",10D,new Unit("个"));
Product p2 = (Product) p1.clone();
System.out.println(p2.getName()+"--"+p2.getPrice()+"--"+p2.getUnit().getName());
System.out.println(p1.getUnit() == p2.getUnit());
p1.getUnit().setName("包");
System.out.println(p2.getUnit().getName());
}
}
class Product implements Cloneable{
private String name;
private Double price;
private Unit unit;
public Product(String name, Double price, Unit unit) {
this.name = name;
this.price = price;
this.unit = unit;
}
public String getName() {
return name;
}
public Double getPrice() {
return price;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", price=" + price +
", unit=" + unit.getName() +
'}';
}
}
class Unit{
private String name;
public Unit(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 深克隆
*/
public class MainPrototype {
public static void main(String[] args) throws CloneNotSupportedException {
Product p1 = new Product("面包",10D,new Unit("个"));
Product p2 = (Product) p1.clone();
System.out.println(p2.getName()+"--"+p2.getPrice()+"--"+p2.getUnit().getName());
System.out.println(p1.getUnit() == p2.getUnit());
p1.getUnit().setName("包");
System.out.println(p2.getUnit().getName());
}
}
class Product implements Cloneable{
private String name;
private Double price;
private Unit unit;
public Product(String name, Double price, Unit unit) {
this.name = name;
this.price = price;
this.unit = unit;
}
public String getName() {
return name;
}
public Double getPrice() {
return price;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
@Override
public Object clone() throws CloneNotSupportedException {
Product p = (Product)super.clone();
Unit clone = (Unit) p.getUnit().clone();
p.setUnit(clone);
return p;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", price=" + price +
", unit=" + unit.getName() +
'}';
}
}
class Unit implements Cloneable{
private String name;
public Unit(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}