• 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 

  • 相关阅读:
    linux开机自启动服务优化设置命令
    yum网络源配置
    CentOS 6一键系统优化 Shell 脚本
    linux系统下find删除目录下除一文件外的所有文件
    linux系统时间同步
    Memcached 查询stats及各项状态解释
    VMWARE 12安装Tools
    win8及以上2012 R2,virtualbox 5.0.20安装centOS6以上各种注意事项
    HTTP的上传文件实例分析
    java中类加载顺序(深入Java)
  • 原文地址:https://www.cnblogs.com/jasenkin/p/1688289.html
Copyright © 2020-2023  润新知