大话设计模式(五)代理模式

代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。

 

 

代理模式基本代码:

using System; using System.Collections.Generic; using System.Text; namespace 代理模式 { class Program { static void Main(string[] args) { Proxy proxy = new Proxy(); proxy.Request(); Console.Read(); } } abstract class Subject { public abstract void Request(); } class RealSubject : Subject { public override void Request() { Console.WriteLine("真实的请求"); } } class Proxy : Subject { RealSubject realSubject; public override void Request() { if (realSubject == null) { realSubject = new RealSubject(); } realSubject.Request(); } } }

 

大话设计模式(五)代理模式_第1张图片

 

using System; using System.Collections.Generic; using System.Text; namespace 代理模式 { class Program { static void Main(string[] args) { SchoolGirl jiaojiao = new SchoolGirl(); jiaojiao.Name = "李娇娇"; Proxy daili = new Proxy(jiaojiao); daili.GiveDolls(); daili.GiveFlowers(); daili.GiveChocolate(); Console.Read(); } } //送礼物 interface GiveGift //代理接口 { void GiveDolls(); void GiveFlowers(); void GiveChocolate(); } class Proxy : GiveGift //代理 { Pursuit gg; public Proxy(SchoolGirl mm) { gg = new Pursuit(mm); } public void GiveDolls() { gg.GiveDolls(); } public void GiveFlowers() { gg.GiveFlowers(); } public void GiveChocolate() { gg.GiveChocolate(); } } class Pursuit : GiveGift //追求者 { SchoolGirl mm; public Pursuit(SchoolGirl mm) { this.mm = mm; } public void GiveDolls() { Console.WriteLine(mm.Name + " 送你洋娃娃"); } public void GiveFlowers() { Console.WriteLine(mm.Name + " 送你鲜花"); } public void GiveChocolate() { Console.WriteLine(mm.Name + " 送你巧克力"); } } class SchoolGirl { private string name; public string Name { get { return name; } set { name = value; } } } }

 

代理模式的应用场景:

你可能感兴趣的:(设计模式,String,null,Class,interface)