原型模式

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace 原型模式
{
    class Resume : ICloneable
    {
        private string name;
        private string timeArea;
        private string company;
        public Resume(string name)
        {
            this.name = name;
        }
        public void setWork(string timeArea, string company)
        {
            this.timeArea = timeArea;
            this.company = company;
        }
        public void Display()
        {
            Console.WriteLine("{0}",name);
            Console.WriteLine("work is {0} {1}",timeArea,company);
        }
        public object Clone()   //通过实现这个方法 实现原型模式
        {
            return (object)this.MemberwiseClone();  //如果类中的属性是值类型,则对该类的属性进行逐位复制,如果是引用类型,则复制引用    

        }                                                                        但不复制引用的对象,因此原始对象及其复本引用同一对象。这是浅表复制
    }
    class Program
    {
        static void Main(string[] args)
        {
   //         Console.WriteLine("ni");
            Resume a = new Resume("jia");
            a.setWork("12","baidu");
            a.Display();
            Resume b = (Resume)a.Clone();
            b.setWork("22","tengxu");
            b.Display();


        }
    }
}


深复制

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace 原型模式2
{
    class Work : ICloneable   //
    {
        private string t;
        public string T
        {
            get { return t; }
            set { t = value; }
        }
        public object Clone()
        {
            return (Object)this.MemberwiseClone();
        }
    }
    class Resume : ICloneable
    {
        private string name;
        private Work w;
        public Resume(string name)
        {
            this.name = name;
        }
        private Resume(Work w)   //
        {
            this.w = (Work)w.Clone();
        }
        public void setW(string t)
        {
            w.T = t;
        }
        public void Display()
        {
            Console.WriteLine("{0}",name);
            Console.WriteLine("{0}",w.T);
        }
        public object Clone()
        {
            Resume obj = new Resume(this.w); //
            obj.name = this.name;
            return obj;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Resume s = new Resume("jia");
            s.setW("12");
            Resume t = (Resume)s.Clone();
            t.setW("13");
            s.Display();
            t.Display();
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值