zoukankan      html  css  js  c++  java
  • 代理模式

    定义:一个类代表另一个类的功能。在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口。通过一个中间层完成两个模块之间的交互。

    通过上面的图片,我们可以看到,通过增加代理来解耦A与C之间的调用,这样可以封装原来C调用A的一些相关细节,转换成C直接调用B中封装后
    的代理方法,则等同于访问A。

    优点: 1、职责清晰。 2、高扩展性。 3、智能化。
    缺点:1、由于在客户端和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求的处理速度变慢。 2、实现代理模式需要额外的工作,有些代理模式的实现非常复杂。

    使用:以下案例通过代理类ProxyImage实现对实体类的一些操作。代理类需要和实体类继承自同一个接口
    1.创建图片接口:

    public interface Image 
    {
       void display();
    }

    2.创建实现接口的实体类。

    public class RealImage implements Image 
    {
       private String fileName;
       public RealImage(String fileName)
       {
          this.fileName = fileName;
          loadFromDisk(fileName);
       }
    
       public Override void display() {
          System.out.println("Displaying " + fileName);
       }
    
       private void loadFromDisk(String fileName){
          System.out.println("Loading " + fileName);
       }
    }
    
    public class ProxyImage implements Image{
       private RealImage realImage;
       private String fileName;
    
       public ProxyImage(String fileName){
          this.fileName = fileName;
       }
    
       public Override void display() {
          if(realImage == null){
             realImage = new RealImage(fileName);
          }
          realImage.display();
       }
    }

    3.当被请求时,使用 ProxyImage 来获取 RealImage 类的对象。

    Image image = new ProxyImage("test_10mb.jpg");
    image.display();
    一直想把之前工作、学习时记录的文档整理到博客上,一方面温故而知新,一方面和大家一起学习 -程序小白
  • 相关阅读:
    虚拟机中对centOS7.4配置静态ip
    mybatis使用中出现的错误!
    http中get和post方法区别
    java中堆和栈的区别
    struts2工作流程
    springmvc工作流程
    JDBC访问数据库流程
    并行程序设计模式-Master-Worker模式-Guarded Suspension模式-不变模式-生产者-消费者模式的理解
    Future模式个人理解
    分布式系统一致性问题和Raft一致性算法
  • 原文地址:https://www.cnblogs.com/wang-jin-fu/p/8320873.html
Copyright © 2011-2022 走看看