设计模式-7-原型模式

说明

通过对自身的浅层的克隆和深层的克隆,能在短期大量生成不同内存区域的相同值的对象

 public class PrototypeA 
    {
        public int i { get; set; }
        public List<string> lstr  { get; set; }
        public PrototypeA()
        {
            lstr = new List<string>();
        }
        public PrototypeA Clone()
        {
            PrototypeA entity = (PrototypeA)this.MemberwiseClone();
            entity.lstr = ((string[])this.lstr.ToArray().Clone()).ToList();
            return entity;
        }
        public void Print()
        {
           foreach(var str in lstr)
            {
                Console.WriteLine(str);
            }
            Console.WriteLine(i);
        }
    }
 Console.WriteLine("---------------");
            PrototypeA prototypeA = new PrototypeA();
            prototypeA.i = 5;
            prototypeA.lstr.Add("1");
            prototypeA.Print();
            Console.WriteLine("---------------");
            var proB = prototypeA.Clone();
            proB.Print();
            Console.WriteLine("---------------");
            proB.i = 7;
            proB.lstr.Add("2");
            proB.Print();
            Console.WriteLine("---------------");
            prototypeA.Print();

 

posted @ 2016-06-15 23:08  MancosZeng  阅读(106)  评论(0编辑  收藏  举报