美文网首页设计模式
设计模式 - 原型模式

设计模式 - 原型模式

作者: Mitchell | 来源:发表于2016-03-16 23:27 被阅读33次
    • 注意深复制与浅赋值的问题
    • 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 ();
    
    
            }
        }
    }
    
    
    

    相关文章

      网友评论

      • pyboy:楼主应该把运行结果也贴出来

      本文标题:设计模式 - 原型模式

      本文链接:https://www.haomeiwen.com/subject/kkpdkttx.html