原型模式:快速的创建一个对象而不需要提供专门的new()操作就可以快速完成对象的创建,这无疑是一种非常有效的方式,快速的创建一个新的对象。
UML图:
示例代码:
public interface IPrototype { IPrototype Clone(); }
[Serializable] public class Prototype1:IPrototype { public string Name { get; set; } public int Age { get; set; } public Prototype2 ClassLevel { get; set; } public IPrototype Clone() { //return (IPrototype)this.MemberwiseClone(); //浅复制 SerializableHelper s = new SerializableHelper(); string target = s.Serializable(this); return s.Derializable<IPrototype>(target); } }
[Serializable] public class Prototype2:IPrototype { public string ClassName { get; set; } public IPrototype Clone() { return (IPrototype)this.MemberwiseClone(); } }
public class SerializableHelper { public string Serializable(object target) { using (MemoryStream stream = new MemoryStream()) { new BinaryFormatter().Serialize(stream, target); return Convert.ToBase64String(stream.ToArray()); } } public object Derializable(string target) { byte[] targetArray = Convert.FromBase64String(target); using (MemoryStream stream = new MemoryStream(targetArray)) { return new BinaryFormatter().Deserialize(stream); } } public T Derializable<T>(string target) { return (T)Derializable(target); } }
static void Main(string[] args) { Prototype2 pro2 = new Prototype2 { ClassName = "一年级" }; Prototype1 pro1 = new Prototype1 { Age = 25, Name = "cys", ClassLevel = pro2 }; var pro11 = (Prototype1)pro1.Clone(); pro11.Name = "wxd";//修改pro11不影响pro1 pro11.ClassLevel.ClassName = "二年级";//修改修改pro11影响pro1,需要深度复制 }