代理模式
代理模式(proxy),为其他对象提供一种代理以控制对这个对象的访问。
故事:为别人做嫁衣
卓贾易喜欢娇娇,自己不敢接近,买了礼物却每次让戴励送给娇娇,一来二去娇娇和戴励好上了,卓贾易为别人做了嫁衣。
代理接口:
GiveGift.cs
1 namespace ProxyPattern 2 { 3 interface GiveGift 4 { 5 void GiveDolls(); 6 void GiveFlowers(); 7 void GiveChocolate(); 8 } 9 }
被追求者类:
SchoolGirl.cs
1 namespace ProxyPattern 2 { 3 class SchoolGirl 4 { 5 private string name; 6 public string Name 7 { 8 get { return name; } 9 set { name = value; } 10 } 11 } 12 }
追求者类:
Pursuit.cs
1 namespace ProxyPattern 2 { 3 class Pursuit:GiveGift //让追求者去实现送礼物接口 4 { 5 SchoolGirl mm; 6 public Pursuit(SchoolGirl mm) 7 { 8 this.mm = mm; 9 } 10 11 public void GiveDolls() 12 { 13 Console.WriteLine(mm.Name + "送你羊娃娃"); 14 } 15 public void GiveFlowers() 16 { 17 Console.WriteLine(mm.Name + "送你鲜花"); 18 } 19 public void GiveChocolate() 20 { 21 Console.WriteLine(mm.Name + "送你巧克力"); 22 } 23 } 24 }
代理类:
Proxy.cs
1 namespace ProxyPattern 2 { 3 class Proxy:GiveGift //让代理也去实现送礼物接口 4 { 5 Pursuit pursuit; 6 public Proxy(SchoolGirl mm) 7 { 8 pursuit = new Pursuit(mm); 9 } 10 public void GiveDolls() 11 { 12 pursuit.GiveDolls(); //在实现方法中去调用追求者类的相关方法 13 } 14 public void GiveFlowers() 15 { 16 pursuit.GiveFlowers(); 17 } 18 public void GiveChocolate() 19 { 20 pursuit.GiveChocolate(); 21 } 22 } 23 }
客户端:
Program.cs
1 namespace ProxyPattern 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 SchoolGirl sGirl = new SchoolGirl(); 8 sGirl.Name = "娇娇"; 9 10 Proxy proxy = new Proxy(sGirl); 11 12 proxy.GiveDolls(); 13 proxy.GiveFlowers(); 14 proxy.GiveChocolate(); 15 16 Console.Read(); 17 } 18 } 19 }
本文来自博客园,作者:一纸年华,转载请注明原文链接:https://www.cnblogs.com/nullcodeworld/p/9364296.html