设计模式-原型模式
用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。
当我们在需要同一个类的大量对象的时候,重复使用new会消耗大量性能,这个时候使用原型模式是一个好的选择。
@Data
@AllArgsConstructor
public class Resume implements Cloneable {
private String name;
private int age;
private Position position;
@Override
protected Resume clone() throws CloneNotSupportedException {
Resume resume = (Resume)super.clone();
resume.setPosition(new Position(this.position.getCompany(), this.position.getTitle()));
return resume;
}
@Data
@AllArgsConstructor
public static class Position{
private String company;
private String title;
}
}
原型模式需要目标类实现clone方法,特别注意的是深浅拷贝的问题。
需要新的实例的时候只需要调用clone方法就好了
public class CloneResume {
public static void main(String[] args) throws Exception {
Resume resume = new Resume("Bob", 18, new Resume.Position("APPLE", "Developer"));
Resume resumeNew = resume.clone();
resume.getPosition().setTitle("CTO");
System.out.println(resume.toString());
System.out.println(resumeNew.toString());
}
}