設計模式 - 原型模式

weixin_34116110發表於2016-03-16
  • 注意深複製與淺賦值的問題
  • C#中如果需要實現深複製,必須實現 ICloneable 介面。
using System;
namespace Factory1
{
    //工作經驗類
    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 (Object)this.MemberwiseClone();
        }
    }
    //簡歷類
    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 ("workExperience:{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;
        }
          }

    class MainClass
    {
        public static void Main (string[] args)
        {
            Resume a = new Resume ("aaa");
            a.SetPersonalInfo ("man", "12");
            a.SetWorkExperience ("1998-2001", "YY Company");

            Resume b = (Resume)a.Clone ();
            b.SetPersonalInfo ("girl", "22");

            Resume c = (Resume)a.Clone ();
            c.SetPersonalInfo ("boy", "66");

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


        }
    }
}


相關文章