欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式 - 原型模式

程序员文章站 2022-06-12 20:18:41
...
  • 注意深复制与浅赋值的问题
  • 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 ();


        }
    }
}