原型模式
最近重读设计模式,理解更上一层楼。
为以便日后翻阅之需特坚持写博客,记录技术点滴,本设计模式系列源码均参考 http://c.biancheng.net/view/1317.html java语言版本的23种设计模式,同时方便没有java基础的同学参阅故翻译成C#系列。
/// <summary> /// 原型模式通常适用于以下场景。 //对象之间相同或相似,即只是个别的几个属性不同的时候。 //对象的创建过程比较麻烦,但复制比较简单的时候。 /// </summary> public class SunWukong : ICloneable { public object Clone() { //注意深拷贝和浅拷贝的问题 SunWukong sunWukong = (SunWukong)this.MemberwiseClone(); return sunWukong; } } public class ProtoTypeCitation { public static void Main(String[] args) { citation obj1 = new citation("张三", "同学:在2016学年第一学期中表现优秀,被评为三好学生。", "韶关学院"); obj1.Display(); citation obj2 = (citation)obj1.Clone(); obj2.SetName("李四"); obj2.Display(); } } public class citation : ICloneable { string name; string info; string college; public citation(string name, string info, string college) { this.name = name; this.info = info; this.college = college; Console.WriteLine("奖状创建成功!"); } public void SetName(string name) { this.name = name; } public string GetName() { return (this.name); } public void Display() { Console.WriteLine(name + info + college); } public object Clone() { Console.WriteLine("奖状拷贝成功!"); return (citation)this.Clone(); } }
浙公网安备 33010602011771号