Proxy Pattern设计模式简单随笔

      在软件系统中,有些对象有时候由于跨越网络或者其他的障碍,而不能够或者不想直接访问另一个对象,如果直接访问会给系统带来不必要的复杂性,这时候可以在客户程序和目标对象之间增加一层中间层,让代理对象来代替目标对象打点一切。这就是Proxy模式。

     代理模式、装饰模式与适配器模式有点类似,都是通过中间层来实现原有对象功能,但它们解决问题的目标不同,其区别为:
     代理模式只是原来对象的一个替身(原来对象约束了代理的行为)。
     装饰模式是对原对象的功能增强。
     适配器模式是要改变原对象的接口。

原有的操作,可是却不能直接使用(假设而已)。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace ProxyPatternSam
 6 {
 7     public abstract class AbstractClass
 8     {
 9         public abstract void Work();
10     }
11 }
12 
13 using System;
14 using System.Collections.Generic;
15 using System.Text;
16 
17 namespace ProxyPatternSam
18 {
19     public  class InheritClass:AbstractClass 
20     {
21 
22         public override void Work()
23         {
24            // throw new Exception("The method or operation is not implemented.");
25             Console.WriteLine("XXXXXXXXXXXXXXXXXXXXXXXXX");
26         }
27     }
28 }
29 

我们可以通过创建一个代理类来使客户端和原有的类连接起来。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace ProxyPatternSam
 6 {
 7     public class ProxyClass:AbstractClass
 8     {
 9         private AbstractClass  instance;//声明需要代理的实例
10         public override void Work()
11         {//作为中间层来调用方法
12            // throw new Exception("The method or operation is not implemented.");
13             if(instance==null)
14             {
15                 instance = new InheritClass();
16             }
17             Console.WriteLine("proxy working!");
18             instance.Work();//调用实例的方法
19 
20         }
21     }
22 }
23 

客户端直接使用代理类来进行操作:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace ProxyPatternSam
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             ProxyClass proxy = new ProxyClass();// 创建代理----》调用方法
12             proxy.Work();
13             Console.ReadLine();
14         }
15     }
16 }

*****************************************************************************

源代码:

/Files/jasenkin/ProxyPatternSam.rar 

原文地址:https://www.cnblogs.com/jasenkin/p/1688289.html