• 《大话设计模式》--原型模式


    题目:编写简历,复制三份,做相应的修改

    以下为深层复制

    public class WorkExperience implements Cloneable {
        private String timeArea;
        private String company;
    
        public String getTimeArea() {
            return timeArea;
        }
    
        public void setTimeArea(String timeArea) {
            this.timeArea = timeArea;
        }
    
        public String getCompany() {
            return company;
        }
    
        public void setCompany(String company) {
            this.company = company;
        }
    
        @Override
        protected Object clone() {
            Object o = null;
            try {
                o = super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return o;
        }
    }
    public class Resume implements Cloneable {
        private String name;
        private String sex;
        private String age;
        private WorkExperience work;
    
        public Resume(String name) {
            this.name = name;
            work = new WorkExperience();
        }
    
        private Resume(WorkExperience work) {
            this.work = (WorkExperience) work.clone();
        }
    
        public void setPersonalInfo(String sex, String age) {
            this.sex = sex;
            this.age = age;
        }
    
        public void setWorkExperience(String timeArea, String company) {
            work.setTimeArea(timeArea);
            work.setCompany(company);
        }
    
        public void display() {
            System.out.println(name + "," + sex + "," + age);
            System.out.println("工作经历:" + work.getTimeArea() + "," + work.getCompany());
        }
    
        @Override
        protected Object clone() {
            Resume obj = new Resume(this.work);
            obj.name = this.name;
            obj.sex = this.sex;
            obj.age = this.age;
            return obj;
        }
    }
    public class Test {
        public static void main(String args[]) {
            Resume a = new Resume("小王");
            a.setPersonalInfo("男", "29");
            a.setWorkExperience("1999-2004", "XX公司");
    
            Resume b = (Resume) a.clone();
            b.setPersonalInfo("男", "25");
    
            Resume c = (Resume) a.clone();
            c.setWorkExperience("1995-2003", "YY公司");
    
            a.display();
            b.display();
            c.display();
        }
    }

    打印结果

    小王,男,29
    工作经历:1999-2004,XX公司
    小王,男,25
    工作经历:1999-2004,XX公司
    小王,男,29
    工作经历:1995-2003,YY公司

    一般在初始化的信息不发生改变的情况下,克隆是最好的方法。这既隐藏了对象创建的细节,又对性能是大大的提高。

  • 相关阅读:
    Go 语言机制之逃逸分析
    类型转换和类型断言
    浅析rune数据类型
    Go 文件操作(创建、打开、读、写)
    字符编码笔记:ASCII,Unicode 和 UTF-8
    cmd.exe启动参数详解
    linux下.so、.ko、.a的区别
    Python 和C#的交互
    Innodb表压缩过程中遇到的坑(innodb_file_format)
    更改mysql的加密方式和密码策略
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/7423869.html
Copyright © 2020-2023  润新知