原型模式(Prototype)

简历复印---原型模式(Prototype)

原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。

.Net在System命名空间中提供了ICloneable接口,其实就是唯一的 一个方法Clone(),只需要实现这个接口就可以实现原型设计模式了。

MemverwiseClone()方法是这样的,如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象,因此,原始对象极其复本引用同一个对象。

“浅复制”是指被复制的对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象。

“深复制”是把引用对象的变了指向复制复制过的新对象,而不是原有的被引用的对象。

简历深复制的实现:

工作经历类

using System;
using System.Collections.Generic;
using System.Text;

namespace ICloneableInfo
{
    public class WorkExperinece :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();
        }
    }
}

简历类:

using System;
using System.Collections.Generic;
using System.Text;

namespace ICloneableInfo
{
    public class Resume : ICloneable
    {
        private int age;
        private string name;
        private string sex;
        private WorkExperinece work;
        public Resume(string name)
        {
            this.name = name;
            work = new WorkExperinece();
        }

        public Resume(WorkExperinece work)
        {
            this.work = (WorkExperinece)work.Clone();
        }
        //设置个人信息
        public void SetPersonalInfo(string sex, int age)
        {
            this.sex = sex;
            this.age = age;
        }

        //设置工作经历
        public void SetWorkExperisence(string timeArea, string company)
        {
            work.WorkDate = timeArea;
            work.Company = company;
        }

        public string  Display()
        {
            string reStr = name + " " + sex + " " + age + "";
            reStr += "工作经历" + work.WorkDate + " " + work.Company;
            return reStr;
        }

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

客户端调用:

 Resume a = new Resume("大鸟");
 a.SetPersonalInfo("男", 23);
 a.SetWorkExperisence("2009.2-2010.8", "厦门XX软件有限公司");

 Resume b = (Resume)a.Clone();

 b.SetWorkExperisence("2008.10-2009.2","厦门YY软件有限公司");

 richTextBox1.Text = a.Display() +"\n" +b.Display();


原文地址:https://www.cnblogs.com/IcefishBingqing/p/1809515.html