码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之代理模式

时间:2017-12-17 11:05:53      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:调用   oid   end   修改   names   结构   thread   body   color   

在代理模式(Proxy Pattern)中,一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。

在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口。

首先创建一个标准的代理模式,我们需要一个抽象接口(不要这个接口也可以)

1   public interface ISubject
2   {
3      bool GetSomething();
4 
5      void DoSomething();
6   }

然后新建一个类模拟去火车站买票的类(被代理类)

 1 namespace 代理模式
 2 {
 3     class RealuSubject:ISubject
 4     {
 5         public RealuSubject()
 6         {
 7             Thread.Sleep(2000);
 8             long lResult = 0;
 9             for (int i = 0; i < 100000000; i++)
10             {
11                 lResult += i;
12             }
13             Console.WriteLine("RealuSubject被构造...");
14         }
15 
16 
17         public bool GetSomething()
18         {
19             Console.WriteLine("坐火车去火车站看看余票信息...");
20             Thread.Sleep(2000);
21             Console.WriteLine("火车站,看到有票的");
22             return true;
23         }
24 
25         public void DoSomething()
26         {
27             Console.WriteLine("开始排队......");
28             Thread.Sleep(2000);
29             Console.WriteLine("终于买到票了.....");
30         }
31     }
32 }

接着创建代理类,这里使用日志代理的功能来演示(也就是在代理类里加入了日志输出的代码)

 1 namespace 代理模式
 2 {
 3     class ProxySubject:ISubject
 4     {
 5         private ISubject _RealuSubject = new RealuSubject();
 6 
 7         public bool GetSomething()
 8         {
 9             Console.WriteLine("GetSomething start....");
10             bool bResult= this._RealuSubject.GetSomething();
11             Console.WriteLine("GetSomething end....");
12             return bResult;
13         }
14 
15         public void DoSomething()
16         {
17             Console.WriteLine("DoSomething start....");
18             this._RealuSubject.DoSomething();
19             Console.WriteLine("DoSomething end....");
20         }
21     }
22 }

最后我们调用代理模式

技术分享图片

技术分享图片

代理模式可以实现AOP的思想,他可以实现很多种功能例如上面的日志代理,数据库代理,延迟代理,权限代理,异常代理

这些都是在代理层给加上去的一些功能,而不修改到原来的代码

设计模式之代理模式

标签:调用   oid   end   修改   names   结构   thread   body   color   

原文地址:http://www.cnblogs.com/BigDong/p/8051233.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!