设计模式——原型模式

原型模式是什么?

用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象

原型模式解决什么问题?

当前有简历类

public class Resume {
    private String name;
    private String sex;
    private String age;
    private String timeArea;
    private String company;

    public Resume(String name) {
        this.name = name;
    }

    public void setPersonInfo(String sex, String age) {
        this.sex = sex;
        this.age = age;
    }

    public void setWorkExperience(String timeArea, String company) {
        this.timeArea = timeArea;
        this.company = company;
    }

    public void display() {
        System.out.println(name + " " + sex + " " + age);
        System.out.println("工作经历 " + timeArea + " " + company);
    }
}

当要生成3份相同的简历时,只能将代码复制3次

Resume resume1 = new Resume("A");
resume1.setPersonInfo("男", "23");
resume1.setWorkExperience("1998-2000", "A公司");

Resume resume2 = new Resume("A");
resume2.setPersonInfo("男", "23");
resume2.setWorkExperience("1998-2000", "A公司");

Resume resume3 = new Resume("A");
resume3.setPersonInfo("男", "23");
resume3.setWorkExperience("1998-2000", "A公司");

resume1.display();
resume2.display();
resume3.display();

原型模式实现

原型模式从一个对象再创建另一个对象,且不需要知道任何创建细节,Java提供了Cloneable

public class Resume implements Cloneable {
    private String name;
    private String sex;
    private String age;
    private String timeArea;
    private String company;

    public Resume(String name) {
        this.name = name;
    }

    public void setPersonInfo(String sex, String age) {
        this.sex = sex;
        this.age = age;
    }

    public void setWorkExperience(String timeArea, String company) {
        this.timeArea = timeArea;
        this.company = company;
    }

    public void display() {
        System.out.println(name + " " + sex + " " + age);
        System.out.println("工作经历 " + timeArea + " " + company);
    }

    @NonNull
    @Override
    protected Resume clone() {
        Resume object = null;
        try {
            object = (Resume) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return object;
    }
}

当构造函数执行时间很长时,调用Clone()初始化可以提高性能

Resume resume1 = new Resume("A");
resume1.setPersonInfo("男", "23");
resume1.setWorkExperience("1998-2000", "A公司");

Resume resume2 = resume1.clone();
resume2.setWorkExperience("2000-2003", "B公司");

Resume resume3 = resume2.clone();
resume3.setPersonInfo("男", "24");

resume1.display();
resume2.display();
resume3.display();

浅拷贝和深拷贝

详见Java中级——Object和Objects

你可能感兴趣的:(#,设计模式,设计模式,原型模式,java)