大话设计模式笔记 原型模式

原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。

 

基本类型与引用类型的区别于关系在efficient java。

http://www.cnblogs.com/linkarl/p/4785329.html

 

浅复制:对象的引用仍然指向原来的对象

深复制:把引用对象的变量指向复制过的新对象

 

我认为一般深复制比较常用。

package prototype;

public class WorkExperience implements Cloneable {
    private String workDate;
    private String company;

    public String getWorkDate() {
        return workDate;
    }

    public void setWorkDate(String workDate) {
        this.workDate = workDate;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public Object Clone() throws CloneNotSupportedException {
        return (Object) this.clone();
    }
}

 

package prototype;

public class Resume implements Cloneable {
    private String name;
    private WorkExperience workExperience;

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

    private Resume(WorkExperience workExperience)
            throws CloneNotSupportedException {
        this.workExperience = (WorkExperience) workExperience.Clone();
    }

    public WorkExperience getWorkExperience() {
        return workExperience;
    }

    public void setWorkExperience(String workData, String company) {
        workExperience.setWorkDate(workData);
        workExperience.setCompany(company);
    }

    public void Display() {
        System.out.println(name);
        System.out.println("WorkExperience: " + workExperience.getWorkDate()
                + workExperience.getCompany());
    }

    public Object Clone() throws CloneNotSupportedException {
        Resume resume = new Resume(this.workExperience);
        resume.name = this.name;
        return resume;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Resume a = new Resume("a");
        a.setWorkExperience("workData", "company");

        Resume b = (Resume) a.Clone();
        b.setWorkExperience("b-workData", "company");

        Resume c = (Resume) b.Clone();
        c.setWorkExperience("c-workData", "company");

        a.Display();
        b.Display();
        c.Display();

    }
}

 

posted @ 2015-09-23 23:19  郁闷紫番薯  阅读(158)  评论(0编辑  收藏  举报