大话设计模式之原型模式
概念:原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Data; 5 6 namespace 原型模式 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Resume a = new Resume("大鸟"); 13 a.SetPersonalInfo("男", "29"); 14 a.SetWorkExperience("1998-2000", "XX公司"); 15 16 Resume b = (Resume)a.Clone(); 17 b.SetWorkExperience("1998-2006", "YY企业"); 18 19 Resume c = (Resume)a.Clone(); 20 c.SetWorkExperience("1998-2003", "ZZ企业"); 21 22 a.Display(); 23 b.Display(); 24 c.Display(); 25 26 Console.Read(); 27 28 } 29 } 30 31 //简历 32 class Resume : ICloneable 33 { 34 private string name; 35 private string sex; 36 private string age; 37 38 private WorkExperience work; 39 40 public Resume(string name) 41 { 42 this.name = name; 43 work = new WorkExperience(); 44 } 45 46 private Resume(WorkExperience work) 47 { 48 this.work = (WorkExperience)work.Clone(); 49 } 50 51 //设置个人信息 52 public void SetPersonalInfo(string sex, string age) 53 { 54 this.sex = sex; 55 this.age = age; 56 } 57 //设置工作经历 58 public void SetWorkExperience(string workDate, string company) 59 { 60 work.WorkDate = workDate; 61 work.Company = company; 62 } 63 64 //显示 65 public void Display() 66 { 67 Console.WriteLine("{0} {1} {2}", name, sex, age); 68 Console.WriteLine("工作经历:{0} {1}", work.WorkDate, work.Company); 69 } 70 71 public Object Clone() 72 { 73 Resume obj = new Resume(this.work); 74 75 obj.name = this.name; 76 obj.sex = this.sex; 77 obj.age = this.age; 78 79 80 return obj; 81 } 82 83 } 84 85 //工作经历 86 class WorkExperience : ICloneable 87 { 88 private string workDate; 89 public string WorkDate 90 { 91 get { return workDate; } 92 set { workDate = value; } 93 } 94 private string company; 95 public string Company 96 { 97 get { return company; } 98 set { company = value; } 99 } 100 101 public Object Clone() 102 { 103 return (Object)this.MemberwiseClone(); 104 } 105 } 106 107 }
注意:其中的Memberwise()方法是这样的,如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象,因此,原始对象及其复本引用同一对象。
原型模式在.Net中的应用:.Net在System命名空间中提供了ICloneable接口,其中就是唯一的一个方法Clone(),这样你就只需要实现这个接口就可以完成原型模式了。
每多学一点知识,就会少些一行代码