赞
踩
1、为什么要用原型模式?
我们可以通过工厂方法模式去new一个对象,但是这个对象的状态是初始的转态,如果我们在开发中需要对象当时的状态,并且需要拷贝它的副本,而不是直接对原对象进行操作,这个时候工厂方法模式就失效了,这时有一种新的模式叫原型模式,它的作用就是拷贝一个对象,并且这个对象和原来的对象的状态一致,这样就满足了我们的要求,原型模式中有两种克隆方法,一种叫深克隆,一种叫浅克隆,区别在于复制原型对象的时候是否复制包含在原型对象中的引用类型的成员变量,且对于浅克隆,我们一般使用c#自带的MemberwiseClone方法,代码如下:
class Student { public int Age { get; set; } public Family _Family { get; set; } public string Name { get; set; } public Student ShallowClone()//浅克隆 { return (Student)this.MemberwiseClone(); } public Student DeepClone()//深克隆 { string jsonStr = JsonConvert.SerializeObject(this, Formatting.Indented); File.WriteAllText("temp.dat", jsonStr); string readStr = File.ReadAllText("temp.dat"); Student student = JsonConvert.DeserializeObject<Student>(readStr); return student; } } class Family { public string Father { get; set; } public string Mother { get; set; } }
客户端调用如下:
Student student1 = new Student();
Student student2 = student1.ShallowClone();
Console.WriteLine(student1 == student2);
Console.WriteLine(student1.Age == student2.Age);
Console.WriteLine(student1.Name == student2.Name);
Console.WriteLine(student1._Family == student2._Family);
Student student3 = student1.DeepClone ();
Console.WriteLine(student1 == student3);
Console.WriteLine(student1.Age == student3.Age);
Console.WriteLine(student1.Name == student3.Name);
Console.WriteLine(student1._Family == student3._Family);
输出:
False
True
True
True
False
True
True
True
程序的执行结果是浅克隆和深克隆的第一个结果都是"false",但是第二个结果是"true",说明对象本身复制了,但是最后一个输出都是True,违背了深克隆的规律,按理说深克隆时,最后一个_Famliy是不相等的,这是因为_Famliy的值都是null导致的,更改客户端调用代码如下:
Student student1 = new Student(); student1.Age = 10; student1.Name = "小王"; Family family = new Family() { Father="爸爸",Mother ="妈妈" }; student1._Family = family; Student student2 = student1.ShallowClone(); Console.WriteLine(student1 == student2); Console.WriteLine(student1.Age == student2.Age); Console.WriteLine(student1.Name == student2.Name); Console.WriteLine(student1._Family == student2._Family); Student student3 = student1.DeepClone (); Console.WriteLine(student1 == student3); Console.WriteLine(student1.Age == student3.Age); Console.WriteLine(student1.Name == student3.Name); Console.WriteLine(student1._Family == student3._Family);
输出:
False
True
True
True
False
True
True
False
这是因为_Family此时不为Null,但是由于是深克隆,所以_Family在栈上也重新开辟了内存。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。