定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
使用场景:要创建大量相同类型的对象时
实现:实现Cloneable接口,该接口是一个标记接口,并没有要实现的方法,不实现会抛出不支持克隆异常。然后重写Object的clone方法即可。
优点:避免写大量new对象的操作,提高性能,在构造方法较复杂时,性能提升越明显
注意点:深拷贝和浅拷贝
代码示例:深拷贝简历类
/**
* 简历类
* @author liuhao
*
*/
public class Resume implements Cloneable{
private String name;
private int age;
private WorkExperience workExperience;
public Resume clone() throws CloneNotSupportedException {
Resume resume = (Resume) super.clone();
WorkExperience workExperience = this.workExperience.clone();
resume.workExperience = workExperience;
return resume;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public WorkExperience getWorkExperience() {
return workExperience;
}
public void setWorkExperience(WorkExperience workExperience) {
this.workExperience = workExperience;
}
@Override
public String toString() {
return "Resume [name=" + name + ", age=" + age + ", workExperience=" + workExperience + "]";
}
}
/**
* 工作经历类
* @author liuhao
*
*/
public class WorkExperience implements Cloneable{
private String company;
public WorkExperience clone() throws CloneNotSupportedException {
return (WorkExperience)super.clone();
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
public class Test implements Cloneable{
public static void main(String[] args) throws CloneNotSupportedException {
Resume resume = new Resume();
resume.setName("张三");
resume.setAge(18);
WorkExperience experience = new WorkExperience();
resume.setWorkExperience(experience);
experience.setCompany("alibaba");
Resume resume2 = resume.clone();
resume2.setName("李四");
resume2.setAge(28);
resume2.getWorkExperience().setCompany("huawei");
System.out.println(resume);
System.out.println(resume2);
}
}
结果: