设计模式(九):代理模式

一、定义

代理模式就是中间层。可以帮助我们增加或者减少对目标类的访问。

二、实例

我在项目中会遇见这样的情况,类A中的方法是protected,但是此时另外一个分继承自A类的B类要使用A中的个别方法。

比如这样:

 public class Collect
    {
        protected void GetJson(string url)
        {
            Console.WriteLine("获取Json.");
        }        
    }

    public class Context
    {
        public void GetHtmlFromUrl(string url)
        {
            //这里想用 Collect中的GetJson()方法
        }
    }

好吧,那就增加一层代理,让代理去搞定:

 public class Collect
    {
        protected void GetJson(string url)
        {
            Console.WriteLine("获取Json.");
        }
    }

    public class JsonProxy : Collect
    {       
        public void GetJsonFromUrl(string url)
        {
            base.GetJson(url);
        }
    }

    public class Context
    {
        private JsonProxy jp = new JsonProxy();
        public void GetJson(string url)
        {
            jp.GetJsonFromUrl(url);
        }
    }

客户端:

Proxy.Context cx = new Proxy.Context();
cx.GetJson("URL");
Console.ReadKey();

正规一点的代理模式:这里我私自加了单例模式在里面

public interface JsonProxy
    {
       void GetJsonFromUrl(string url);
    }
   
    public class Collect:JsonProxy
    {
        protected void GetJson(string url)
        {
            Console.WriteLine("执行受保护方法GetJson(),获取Json.");
        }

        public void GetJsonFromUrl(string url)
        {
            this.GetJson(url);
        }
    }

    public class Proxy : JsonProxy
    {
        private static Collect collect { get; set; }      
        public static Proxy Instance { get; set; }
        private Proxy() { }
        static Proxy()
        {
            Instance = new Proxy();
            collect = new Collect();
            Console.WriteLine("单例 : 代理.");
        }      
        public void GetJsonFromUrl(string url)
        {
            collect.GetJsonFromUrl(url);
        }
    } 

客户端:

//-----------------------代理模式---------------------
System.Threading.Tasks.Parallel.For(0, 500, t => { Proxy.Proxy.Instance.GetJsonFromUrl("URL"); });
Console.ReadKey();

 三、优缺点

优:

  1. 代理模式能够将调用用于真正被调用的对象隔离,在一定程度上降低了系统的耦合度;
  2. 代理对象在客户端和目标对象之间起到一个中介的作用,这样可以起到对目标对象的保护。代理对象可以在对目标对象发出请求之前进行一个额外的操作,例如权限检查等。

缺:

  1.  由于在客户端和真实主题之间增加了一个代理对象,所以会造成请求的处理速度变慢
  2. 实现代理类也需要额外的工作,从而增加了系统的实现复杂度。
原文地址:https://www.cnblogs.com/sunchong/p/5124591.html