zoukankan      html  css  js  c++  java
  • 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 

  • 相关阅读:
    关于python的open函数encoding的入参
    控制台输出的log加颜色
    logging把log写到控制台
    合并两个list里的字典
    关于字典数组和元组合并
    python字典做入参调用时要写成**K这种形式
    python在循环中将含变量的字典加到列表中(问题:如果写法不当,会导致最后赋值的变量覆盖列表中前面赋值的变量)
    给定列表,按照列表内容获取excel指定列名下的内容
    selenum报错element is not attached to the page document
    python selenium获取input输入框中的值
  • 原文地址:https://www.cnblogs.com/jasenkin/p/1688289.html
Copyright © 2011-2022 走看看