为其他对象提供一种代理以控制对这个对象的访问
1、远程代理:在.net中,引用外部的WebService就是一种代理模式。
2、虚拟代理:根据需要,创建开销很大的对象。通过它来存放,需要很长事件实例化的真实对象。
3、安全代理:控制真实对象访问时的权限。
4、只能引用:调用真实对象的时候,代理处理另外一些事。


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Proxy { class SchoolGirl { private string name; public string Name { get { return name; } set { name = value; } } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Proxy { interface IGiveGift//代理接口 { void GiveDolls(); void GiveFlower(); void GiverChocolate(); } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Proxy { class Pursuit : IGiveGift//唯一变化就是让“追求者” 去实现“送礼物” 接口 { 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 + "送你巧克力!"); } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Proxy { class Proxy:IGiveGift//proxy 类保存一个引用,使得代理可以访问实体,并提供一个与subject的接口相同的接口,这样代理就可以用来替代实体 { Pursuit gg; public Proxy(SchoolGirl mm) { gg = new Pursuit(mm); } public void GiveDolls() { gg.GiveDolls(); } public void GiveChocolate() { gg.GiveChocolate(); } public void GiveFlowers() { gg.GiveFlowers(); } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Proxy { class Program { static void Main(string[] args) { SchoolGirl jiaojiao = new SchoolGirl(); jiaojiao.Name = "娇娇"; //这里创建了proxy对象,但是,这个对象最终运行的代码,都是在Pursuit类中具体实现的。 Proxy daili = new Proxy(jiaojiao); daili.GiveChocolate(); daili.GiveDolls(); daili.GiveFlowers(); } } }