zoukankan      html  css  js  c++  java
  • 设计模式之原型模式

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

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

     

  • 相关阅读:
    再谈iOS 7的手势滑动返回功能
    CGContextRef用法
    UIView的layoutSubviews和drawRect方法何时调用
    layoutSubviews何时调用的问题
    iOS应用开发最佳实践:编写高质量的Objective-C代码
    WWDC2014之App Extensions学习笔记
    定制iOS 7中的导航栏和状态栏
    从客户端中检测到有潜在危险的 Request.Form 值
    async and await 简单的入门
    C# Dictionary学习
  • 原文地址:https://www.cnblogs.com/JsonZhangAA/p/5503139.html
Copyright © 2011-2022 走看看