原型模式
由于Object类没有实现Cloneable接口,所以某一个类在使用clone()方法的时候一定要实现 Cloneable 接口,否则会抛出异常。
clone()方法复制的类属于浅拷贝
解决浅拷贝的问题,可以使用spring的BeanUtils的方法copy,或者使用序列号和反序列化
public class Prototype {
public static void main(String[] args) throws CloneNotSupportedException {
Product product = new Product();
product.setName("abc");
System.out.println(product);
Product clone = product.clone();
System.out.println(clone);
System.out.println(product.equals(clone));
}
}
class Product implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Product clone() throws CloneNotSupportedException {
return (Product)super.clone();
}
}