码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之原型模式

时间:2016-05-17 21:13:17      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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

.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();
        }
    }
}

 技术分享

设计模式之原型模式

标签:

原文地址:http://www.cnblogs.com/JsonZhangAA/p/5503139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!