1.介绍
原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,
根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,
这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
2.示例
[Serializable] public class StudentProperty { private StudentProperty()//让我们创建对象的时候,麻烦一点 { long lRsult = 0; for (int i = 0; i < 1000000000; i++) { lRsult += i; } Console.WriteLine("构造函数计算完成 {0}", lRsult); } private static StudentProperty _StudentProperty = null; static StudentProperty() { _StudentProperty = new StudentProperty(); _StudentProperty.Name = "tumi"; _StudentProperty.Class = new Advanced() { Id = 1, Name = "Advanced" }; } /// <summary> /// 原型模式:解决对象重复创建的问题 /// 通过MemberwiseClone来clone新对象,内存操作,直接复制的,避免重复创建 /// </summary> /// <returns></returns> public static StudentProperty Clone() { StudentProperty studentCopy = (StudentProperty)_StudentProperty.MemberwiseClone(); return studentCopy; } public int Id { get; set; } public string Name { get; set; } public DateTime Now { get; set; } public Advanced Class { get; set; } } [Serializable] public class Advanced { public int Id { get; set; } public string Name { get; set; } }
public class SerializeHelper { public static string Serializable(object target) { using (MemoryStream stream = new MemoryStream()) { new BinaryFormatter().Serialize(stream, target); return Convert.ToBase64String(stream.ToArray()); } } public static T Derializable<T>(string target) { byte[] targetArray = Convert.FromBase64String(target); using (MemoryStream stream = new MemoryStream(targetArray)) { return (T)(new BinaryFormatter().Deserialize(stream)); } } public static T DeepClone<T>(T t) { return Derializable<T>(Serializable(t)); } }
/// <summary> /// 1 原型模式 /// 2 浅表复制和深表复制 /// </summary> class Program { static void Main(string[] args) { StudentProperty studentProperty1 = StudentProperty.Clone(); studentProperty1.Name = "One"; studentProperty1.Id = 1; studentProperty1.Now = DateTime.Now; StudentProperty studentProperty2 = StudentProperty.Clone(); studentProperty2.Name = "Two"; studentProperty2.Id = 2; studentProperty2.Now = DateTime.Now.AddDays(1); studentProperty2.Class.Name = "ClassName"; StudentProperty studentProperty3 = SerializeHelper.Derializable<StudentProperty>(SerializeHelper.Serializable(studentProperty2));//借助序列化,实现深克隆 studentProperty3.Class.Name = "ClassName"; Console.Read(); } }