标签:
通过实现对象可以复制自身,已现有自身对象为基础克隆出新对象,再在新对象上进行修改得到我们想要的实例。其本质为克隆,快速创建对象。
类图
1 public class ProtoSubject : ICloneable 2 { 3 4 public string Property1 { get; set; } 5 public string Property2 { get; set; } 6 public string Property3 { get; set; } 7 /// <summary> 8 /// 克隆(克隆的话,一般设为深复制) 9 /// </summary> 10 /// <returns></returns> 11 public object Clone() 12 { 13 using (Stream s = new MemoryStream()) 14 { 15 BinaryFormatter formatter = new BinaryFormatter(); 16 formatter.Serialize(s, this); 17 s.Seek(0, SeekOrigin.Begin); 18 return formatter.Deserialize(s); 19 } 20 } 21 /// <summary> 22 /// 浅复制 23 /// </summary> 24 /// <returns></returns> 25 public object ShadowClone() 26 { 27 return this.MemberwiseClone(); 28 } 29 } 30 31 public class Client 32 { 33 public void TestProtoType() 34 { 35 ProtoSubject subject = new ProtoSubject() 36 { 37 Property1 = "00001", 38 Property2 = "00002", 39 Property3 = "009", 40 }; 41 //当现在需要一个和subject一样的对象,只是property3为“hello world”时,我们难道要重新见一个对象并重新使用初赋值语句? 42 //而ProtoSubject已经有自身的克隆功能了,我们只需克隆一个新对象,并将需改变的属性设成我们要设置的值就可以了。 43 ProtoSubject subject2 = (ProtoSubject)subject.Clone(); 44 } 45 }
其实这个模式非常简单,也有有些所谓的建议:类都应该实现自身的克隆方法。
但也不是这样的,自身的克隆现在基本上不用,而是通过第三方帮助类来实现,例如:
1 public class CloneHelper<T> where T:class 2 { 3 public static T Clone(T t) 4 { 5 using (Stream stream = new MemoryStream()) 6 { 7 BinaryFormatter formatter = new BinaryFormatter(); 8 formatter.Serialize(stream, t); 9 stream.Seek(0, SeekOrigin.Begin); 10 return (T)formatter.Deserialize(stream); 11 } 12 } 13 }
我们只需调用上面的类中的静态方法就可以实现对现有类的克隆了。所以对原型模式不是很感冒...
标签:
原文地址:http://www.cnblogs.com/Joy-et/p/4888476.html