设计模式(九):代理模式
一、定义
代理模式就是中间层。可以帮助我们增加或者减少对目标类的访问。
二、实例
我在项目中会遇见这样的情况,类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();
三、优缺点
优:
- 代理模式能够将调用用于真正被调用的对象隔离,在一定程度上降低了系统的耦合度;
- 代理对象在客户端和目标对象之间起到一个中介的作用,这样可以起到对目标对象的保护。代理对象可以在对目标对象发出请求之前进行一个额外的操作,例如权限检查等。
缺:
- 由于在客户端和真实主题之间增加了一个代理对象,所以会造成请求的处理速度变慢
- 实现代理类也需要额外的工作,从而增加了系统的实现复杂度。
更多精彩原创心得,请关注微信公众号: 梯形

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?