大话设计-原型模式

克隆的深复制,浅复制。引用类型涉及深复制,深复制要考虑深几层,有没有可能出现死循环。

using System;
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Resume a = new Resume("大鸟");
            a.SetPersonalInfo("", "24");
            a.SetWorkExperience("1998-2020", "XX公司");
            Resume b = (Resume)a.Clone();
            b.SetWorkExperience("2020-2006", "YY企业");
            Resume c = (Resume)a.Clone();
            c.SetWorkExperience("2012-2300", "ZZ企业");

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

            Console.Read();
        }
    }

    class WorkExperience : ICloneable
    {
        public object Clone()
        {
            // 浅复制
            return this.MemberwiseClone();
        }

        private string workDate;

        public string WorkDate
        {
            get { return workDate; }
            set { workDate = value; }
        }

        private string company;

        public string Company
        {
            get { return company; }
            set { company = value; }
        }
    }

    class Resume : ICloneable
    {
        private string name;
        private string sex;
        private string age;

        private WorkExperience work;

        private Resume(WorkExperience work)
        {
            // 深复制
            this.work = (WorkExperience)work.Clone();
        }

        public Resume(string name)
        {
            this.name = name;
            this.work = new WorkExperience();
        }

        public void SetPersonalInfo(string sex, string age)
        {
            this.sex = sex;
            this.age = age;
        }

        public void SetWorkExperience(string workDate, string company)
        {
            this.work = new WorkExperience();
            this.work.WorkDate = workDate;
            this.work.Company = company;
        }

        public void Display()
        {
            Console.WriteLine("{0},{1},{2}", name, sex, age);
            Console.WriteLine("工作经历:{0},{1}", work.WorkDate, work.Company);
        }

        public Object Clone()
        {
            Resume obj = new Resume(this.work);
            obj.name = this.name;
            obj.sex = this.sex;
            obj.age = this.age;
            return obj;
        }
    }
}

 

posted @ 2020-04-13 22:29  舒碧  阅读(127)  评论(0编辑  收藏  举报