代理设计模式还不会?2分钟搞定

概述

代理模式就是给某一个对象提供一个代理,并由代理对象控制对原对象的引用。在一些情况下,一个客户不想或者不能直接引用一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。例如电脑桌面的快捷方式就是一个代理对象,快捷方式是它所引用的程序的一个代理
代理模式一般又分为安全代理,虚拟代理 ,远程代理。.

类图

代理设计模式还不会?2分钟搞定

需求

老王想邀请马冬梅喝酒,抽烟,穿JK,但老王不善言谈,有点羞涩,只能让其秘书出面邀请,最后他陪马冬梅抽烟,喝酒、穿JK。

使用代理模式的代码

public class ClassFlower{    public string  Name { get; set; }    public ClassFlower(string name)    {        Name=name;    }}/// <summary>/// 不管是代理还是十几人都需要做的共同动作/// </summary>public interface ISubject{    void GiveSmoking();    void GiveBeer();    void GiveJK();}/// <summary>/// 实际人/// </summary>public class RealLaoWang : ISubject{    private readonly ClassFlower _classFlower;
    public RealLaoWang(ClassFlower classFlower)    {        _classFlower = classFlower;    }    public void GiveBeer()    {        Console.WriteLine($"{_classFlower.Name}:请你喝酒");    }
    public void GiveJK()    {        Console.WriteLine($"{_classFlower.Name}:请你穿JK");    }
    public void GiveSmoking()    {        Console.WriteLine($"{_classFlower.Name}:请你抽烟");    }}/// <summary>/// 代理人/// </summary>public class Proxy : ISubject{    private readonly RealLaoWang _realLaoWang;
    public Proxy(RealLaoWang realLaoWang)    {        _realLaoWang = realLaoWang;    }    public void GiveBeer()    {        _realLaoWang.GiveBeer();    }
    public void GiveJK()    {        _realLaoWang.GiveJK();    }
    public void GiveSmoking()    {        _realLaoWang.GiveSmoking();    }
//C#控制台调用ClassFlower classFlower = new ClassFlower("马冬梅");RealLaoWang realLaoWang=new RealLaoWang(classFlower);// 生成代理对象,传入被代理的对象Proxy proxy=new Proxy(realLaoWang);ISubject subject = proxy;subject.GiveBeer();subject.GiveJK();subject.GiveSmoking();

代理设计模式还不会?2分钟搞定

代理模式的优缺点

优点:
  1. 代理模式能够将调用用于真正被调用的对象隔离,在一定程度上降低了系统的耦合度;
  2. 代理对象在客户端和目标对象之间起到一个中介的作用,这样可以起到对目标对象的保护。代理对象可以在对目标对象发出请求之前进行一个额外的操作,例如权限检查等。
缺点:
  1.  由于在客户端和真实主题之间增加了一个代理对象,所以会造成请求的处理速度变慢。
  2. 实现代理类也需要额外的工作,从而增加了系统的实现复杂度。

总结

到这里,代理模式的介绍就结束了,代理模式就是提供了对目标对象访问的代理,有没有发现、设计模式越往后面学习越简单,当然了,有可能也越学越晕,如果发现学习的比较乱、晕,建议前面的文章多看几遍,自己举例实操反复练习巩固下。