大话设计-代理模式
记录大话设计学习过程。
代理模式:代理者为其他对象提供代理,以控制对真实对象的访问。
用户调用代理者,代理者通过真实的对象引用让对象去做事情。但是代理者可以附加一些功能,然后才让真实对象去做事情。
代理模式运用案例:WebService生成代理访问服务,虚拟代理、安全代理(控制真实对象访问时的权限)、智能引用。
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { var girl = new SchoolGirl("邓紫棋"); Proxy proxy = new Proxy(girl); proxy.GiveFlowers(); proxy.GiveChocolate(); proxy.GiveDolls(); } } interface GiveGift { void GiveDolls(); void GiveFlowers(); void GiveChocolate(); } class Pursuit : GiveGift { SchoolGirl girl; public Pursuit(SchoolGirl girl) { this.girl=girl; } public void GiveChocolate() { Console.WriteLine("送巧克力"); } public void GiveDolls() { Console.WriteLine("送洋娃娃"); } public void GiveFlowers() { Console.WriteLine("送花"); } } class Proxy : GiveGift { Pursuit Pursuit; public Proxy(SchoolGirl girl) { Pursuit = new Pursuit(girl); } public void GiveChocolate() { this.Pursuit.GiveChocolate(); } public void GiveDolls() { this.Pursuit.GiveDolls(); } public void GiveFlowers() { this.Pursuit.GiveFlowers(); } } internal class SchoolGirl { public string Name { get; set; } public SchoolGirl(string name) { this.Name = name; } } }
View Code
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { Proxy proxy = new Proxy(); proxy.Request(); } } abstract class Subject { public abstract void Request(); } class RealSubject : Subject { public override void Request() { Console.WriteLine("真实对象在请求"); } } class Proxy : Subject { RealSubject realSubject; public Proxy() { this.realSubject = new RealSubject(); } public override void Request() { // 写一堆附加功能代码..... realSubject.Request(); } } }
赞 (0)