设计模式之原型模式

来源:互联网 发布:网络新媒体专业课程 编辑:程序博客网 时间:2024/06/07 05:28

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

.NET在System命名空间中提供了ICloneable接口,其中就是唯一的一个方法Clone(),这样你就只需要实现这个接口就可以完成原型模式。(选至《大话设计模式》)

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

复制代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 原型模式{    class C:ICloneable    {        private string address;        public string Address        {            get            {                return address;            }            set            {                address = value;            }        }        public object Clone()        {            return (object)this.MemberwiseClone();        }    }    class A : ICloneable    {        private string name;        private string sex;        public C c = new C();        public void SexC(C Sc)        {            this.c = (C)Sc.Clone();        }        public string Name        {            get            {                return name;            }            set            {                name = value;            }        }        public string Sex        {            get            {                return sex;            }            set            {                sex = value;            }        }        public A(string Sname, string Ssex)        {            this.name = Sname;            this.sex = Ssex;        }        public void show()        {            Console.WriteLine("姓名为:{0}", name);            Console.WriteLine("性别为:{0}", sex);            Console.WriteLine("工作地点:{0}", c.Address);        }        public object Clone()        {            return (object)this.MemberwiseClone();        }    }    class Program    {        static void Main(string[] args)        {            C c = new C();            c.Address = "湖北";            A a = new A("张杨", "");            a.SexC(c);            c.Address = "深圳";            A a1 = (A)a.Clone();            a1.SexC(c);            a.show();            a1.show();            Console.ReadKey();        }    }}
复制代码

 

0 0
原创粉丝点击