1. 程式人生 > >設計模式(六):原型模式——深複製

設計模式(六):原型模式——深複製

原型模式(Prototype):用原型例項指定建立物件的種類,並且通過拷貝這些原型建立新的物件。

深複製:把引用物件的變數指向複製到新物件,而不是原有物件的引用

    /// <summary>
    /// 工作經歷
    /// </summary>
    class WorkExperience:ICloneable
    {
        private string workDate;
        public string WorkDate
        {
            get { return workDate; }
            set { workDate = value; }
        }

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

        public Object Clone()
        {
            return MemberwiseClone();
        }
    }
    /// <summary>
    /// 簡歷
    /// </summary>
    class Resume : ICloneable
    {
        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 workDate, string company)
        {
            work.WorkDate = workDate;
            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()
        {
            var obj = new Resume(this.work);
            obj.name = this.name;
            obj.sex = this.sex;
            obj.age = this.age;
            return obj;
        }
    }
    /// <summary>
    /// 執行主體
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Resume("大鳥");
            a.SetPersonalInfo("男", "29");
            a.SetWorkExperience("1999-2000", "XX公司");

            var b = (Resume)a.Clone();
            b.SetWorkExperience("1998-2005", "YY公司");

            var c = (Resume)a.Clone();
            c.SetPersonalInfo("男", "24");

            a.Display();
            b.Display();
            c.Display();
            Console.Read();
        }
    }

執行結果: