题目:A追B,但是羞于表示,所以A通过C给B一直送礼物以讨得欢心。
分析:
根据就分为三个类,SchoolGirl一个类,这个类只需要获得名字就好了;Pursuit一个类,这个类需要实现送礼物这个方法,需要设定他的追求对象是SchoolGirl;Proxy一个类,作为中间人,他并未准备礼物,所以他需要调用Pursuit的礼物类,同时他需要联系到SchoolGirl,已达到将礼物送至她手上的功能。
接口:

1 /** 2 * 接口用于描述一组类的公共方法/公共属性. 3 * 它不实现任何的方法或属性,只是告诉继承它的类《至少》要实现哪些功能, 4 * 继承它的类可以增加自己的方法. 5 */ 6 interface GiveGift 7 { 8 void GiveDolls(); 9 void GiveFlowers(); 10 void GiveChocolate(); 11 }
SchoolGirl类:

1 class SchoolGirl 2 { 3 private string name; 4 5 public string Name 6 { 7 get { return name; } 8 set { name = value; } 9 } 10 }
Pursuit类:

1 class Pursuit : GiveGift 2 { 3 SchoolGirl girl; 4 public Pursuit(SchoolGirl mm) 5 { 6 this.girl = mm; 7 } 8 9 public void GiveDolls() 10 { 11 Console.WriteLine("give dolls for " + girl.Name); 12 } 13 public void GiveFlowers() 14 { 15 Console.WriteLine("give flowers for " + girl.Name); 16 } 17 public void GiveChocolate() 18 { 19 Console.WriteLine("give chocolate for " + girl.Name); 20 } 21 }
Proxy类:

1 class Proxy : GiveGift 2 { 3 Pursuit boy; 4 public Proxy(SchoolGirl mm) 5 { 6 boy = new Pursuit(mm); 7 } 8 public void GiveDolls() 9 { 10 boy.GiveDolls(); 11 } 12 public void GiveFlowers() 13 { 14 boy.GiveFlowers(); 15 } 16 public void GiveChocolate() 17 { 18 boy.GiveChocolate(); 19 } 20 }
主函数:

1 static void Main(string[] args) 2 { 3 SchoolGirl girl = new SchoolGirl(); 4 girl.Name = "Pretty"; 5 6 Proxy someone = new Proxy(girl); 7 8 someone.GiveDolls(); 9 someone.GiveFlowers(); 10 someone.GiveChocolate(); 11 12 Console.Read(); 13 }
注:文中所有代码及知识点均来自于《大话设计模式》,本人属于边学边看边敲代码边总结的阶段。