代理模式

来源:互联网 发布:上海数据港的竞争对手 编辑:程序博客网 时间:2024/05/21 17:29

本文讲述代理模式(Proxy Pattern)的定义,作用,使用场景等。

定义及作用

代理模式由三部分组成:使用方(Client),代理类(Proxy)和实际的类(Real)。Proxy 依赖 Real,除 Real 之外,Proxy 还会有其他的代码逻辑,用于保护性的检查、缓存耗时资源等用途。Client 通过 Proxy 来访问 Real。

所以,Proxy 更像是 Real 的一层包装或代理。Client 使用 Proxy 就跟使用 Real 是一样的,因为二者实现了同样的接口。



uml 图

使用场景

远程代理(Remote Proxy)

该情景由两部分组成:本地对象和远程对象(存在于另一个地址空间)。本地对象是远程对象的代表,本地对象的方法调用最终会转化为远程对象的方法调用。

虚拟代理(Virtual Proxy)

对耗时严重的操作,如 IO,可以通过代理的方式,在需要的时候才去执行,并通过缓存的形式避免多次执行,而这一切都是对 Client 保持透明的。具体见下节的代码示例。

保护代理(Protection Proxy)

增加保护性的检查逻辑,以此控制访问权限。

代码示例

interface Image {    public void displayImage();}//on System A class RealImage implements Image {    private String filename = null;    /**     * Constructor     * @param filename     */    public RealImage(final String filename) {         this.filename = filename;        loadImageFromDisk();    }    /**     * Loads the image from the disk     */    private void loadImageFromDisk() {        System.out.println("Loading   " + filename);    }    /**     * Displays the image     */    public void displayImage() {         System.out.println("Displaying " + filename);     }}//on System B class ProxyImage implements Image {    private RealImage image = null;    private String filename = null;    /**     * Constructor     * @param filename      */    public ProxyImage(final String filename) {         this.filename = filename;     }    /**     * Displays the image     */    public void displayImage() {        if (image == null) {           image = new RealImage(filename);        }         image.displayImage();    }}class ProxyExample {   /**    * Test method    */   public static void main(String[] args) {        final Image IMAGE1 = new ProxyImage("HiRes_10MB_Photo1");        final Image IMAGE2 = new ProxyImage("HiRes_10MB_Photo2");        IMAGE1.displayImage(); // loading necessary        IMAGE1.displayImage(); // loading unnecessary        IMAGE2.displayImage(); // loading necessary        IMAGE2.displayImage(); // loading unnecessary        IMAGE1.displayImage(); // loading unnecessary    }}

程序运行输出:

Loading   HiRes_10MB_Photo1Displaying HiRes_10MB_Photo1Displaying HiRes_10MB_Photo1Loading   HiRes_10MB_Photo2Displaying HiRes_10MB_Photo2Displaying HiRes_10MB_Photo2Displaying HiRes_10MB_Photo1

参考

  • Proxy pattern
0 0
原创粉丝点击