您的位置:首页 > 其它

设计模式-7-原型模式

2016-06-15 23:08 225 查看
说明

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

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: