1. 延迟初始化

2. 虚拟代理(virtual proxy)

原文地址:   http://www.oodesign.com/proxy-pattern.html

Intent

  • The intent of this pattern is to provide a 《Placeholder》 for an object to control references to it.

Implementation

The figure below shows a UML class diagram for the Proxy Pattern:

The participants classes in the proxy pattern are:

    • Subject - Interface implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.
    • Proxy
      • Maintains a reference that allows the Proxy to access the RealSubject.
      • Implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject.
      • Controls access to the RealSubject and may be responsible for its creation and deletion.
      • Other responsibilities depend on the kind of proxy.
    • RealSubject - the real object that the proxy represents.

Applicability & Examples

The Proxy design pattern is applicable when there is a need to control access to an Object, as well as when there is a need for a sophisticated reference to an Object. Common Situations where the proxy pattern is applicable are:

    • Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand (For example creating the RealSubject object only when the doSomething method is invoked).
    • Remote Proxies: providing a local representation for an object that is in a different address space. A common example is Java RMI stub objects. The stub object acts as a proxy where invoking methods on the stub would cause the stub to communicate and invoke methods on a remote object (called skeleton) found on a different machine.
    • Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.
    • Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.

Example - Virtual Proxy Example.

Consider an image viewer program that lists and displays high resolution photos. The program has to show a list of all photos however it does not need to display the actual photo until the user selects an image item from a list.

The code below shows the Image interface representing the Subject. The interface has a single method showImage() that the Concrete Images must implement to render an image to screen.

package proxy;

/**
* Subject Interface
*/
public interface Image { public void showImage(); }

The code below shows the Proxy implementation, the image proxy is a virtual proxy that creates and loads the actual image object on demand, thus saving the cost of loading an image into memory until it needs to be rendered:

package proxy;

/**
* Proxy
*/
public class ImageProxy implements Image { /**
* Private Proxy data
*/
private String imageFilePath; /**
* Reference to RealSubject
*/
private Image proxifiedImage; public ImageProxy(String imageFilePath) {
this.imageFilePath= imageFilePath;
} @Override
public void showImage() { // create the Image Object only when the image is required to be shown proxifiedImage = new HighResolutionImage(imageFilePath); // now call showImage on realSubject
proxifiedImage.showImage(); } }

The code below displays the RealSubject Implementation, which is the concrete and heavyweight implementation of the image interface. The High resolution image, loads a high resolution image from disk, and renders it to screen when showImage() is called.

package proxy;

/**
* RealSubject
*/
public class HighResolutionImage implements Image { public HighResolutionImage(String imageFilePath) { loadImage(imageFilePath);
} private void loadImage(String imageFilePath) { // load Image from disk into memory
// this is heavy and costly operation
} @Override
public void showImage() { // Actual Image rendering logic } }

The code below illustrates a sample image viewer program; the program simply loads three images, and renders only one image, once using the proxy pattern, and another time directly. Note that when using the proxy pattern, although three images have been loaded, the High resolution image is not loaded into memory until it needs to be rendered, while in the part not using the proxy, the three images are loaded into memory although one of them is actually rendered.

package proxy;

/**
* Image Viewer program
*/
public class ImageViewer { public static void main(String[] args) { // assuming that the user selects a folder that has 3 images
//create the 3 images
Image highResolutionImage1 = new ImageProxy("sample/veryHighResPhoto1.jpeg");
Image highResolutionImage2 = new ImageProxy("sample/veryHighResPhoto2.jpeg");
Image highResolutionImage3 = new ImageProxy("sample/veryHighResPhoto3.jpeg"); // assume that the user clicks on Image one item in a list
// this would cause the program to call showImage() for that image only
// note that in this case only image one was loaded into memory
highResolutionImage1.showImage(); // consider using the high resolution image object directly
Image highResolutionImageNoProxy1 = new HighResolutionImage("sample/veryHighResPhoto1.jpeg");
Image highResolutionImageNoProxy2 = new HighResolutionImage("sample/veryHighResPhoto2.jpeg");
Image highResolutionImageBoProxy3 = new HighResolutionImage("sample/veryHighResPhoto3.jpeg"); // assume that the user selects image two item from images list
highResolutionImageNoProxy2.showImage(); // note that in this case all images have been loaded into memory
// and not all have been actually displayed
// this is a waste of memory resources } }

Specific problems and implementation

Java Remote Method Invocation (RMI)

In java RMI an object on one machine (executing in one JVM) called a client can invoke methods on an object in another machine (another JVM) the second object is called a remote object. The proxy (also called a stub) resides on the client machine and the client invokes the proxy in as if it is invoking the object itself (remember that the proxy implements the same interface that RealSubject implements). The proxy itself will handle communication to the remote object, invoke the method on that remote object, and would return the result if any to the client. The proxy in this case is a Remote proxy.

3. 保值器(value holder)

4. 备份(ghost)

java 四种实现延迟加载的方法的更多相关文章

  1. Java四种引用包括强引用,软引用,弱引用,虚引用。

    Java四种引用包括强引用,软引用,弱引用,虚引用. 强引用: 只要引用存在,垃圾回收器永远不会回收Object obj = new Object();//可直接通过obj取得对应的对象 如obj.e ...

  2. jsp中四种传递参数的方法

    jsp中四种传递参数的方法如下: 1.form表单 2.request.setAttribute();和request.getAttribute(); 3.超链接:<a herf="i ...

  3. 线程池是什么?Java四种线程池的使用介绍

    使用线程池的好处有很多,比如节省系统资源的开销,节省创建和销毁线程的时间等,当我们需要处理的任务较多时,就可以使用线程池,可能还有很多用户不知道Java线程池如何使用?下面小编给大家分享Java四种线 ...

  4. java四种引用及在LeakCanery中应用

    java 四种引用 Java4种引用的级别由高到低依次为: StrongReference > SoftReference > WeakReference > PhantomRefe ...

  5. java四种引用与回调函数

    JAVA四种引用 java对象的引用包括: 强引用 软引用 弱引用 虚引用 Java中提供这四种引用类型主要有两个目的: 第一是可以让程序员通过代码的方式决定某些对象的生命周期: 第二是有利于JVM进 ...

  6. Java四种访问修饰符

    Java 四种访问权限 一.概述 访问等级比较:public > protected > default > private 无论是方法还是成员变量,这四种访问权限修饰符作用都一样 ...

  7. javascript四种类型识别的方法

    × 目录 [1]typeof [2]instanceof [3]constructor[4]toString 前面的话 javascript有复杂的类型系统,类型识别则是基本的功能.javascrip ...

  8. Java 四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor

    介绍new Thread的弊端及Java四种线程池的使用,对Android同样适用.本文是基础篇,后面会分享下线程池一些高级功能. 1.new Thread的弊端执行一个异步任务你还只是如下new T ...

  9. Java四种线程池

    Java四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor 时间:20 ...

随机推荐

  1. Linux命令运行监测和软件安装

    监测命令的运行时间 time command $ time sleep 5 real 0m5.003s # 程序开始至结束的时间,包括其它进程占用的时间片和IO时间 user 0m0.001s # 进 ...

  2. CAD执行一个带参数的命令(com接口VB语言)

    主要用到函数说明: MxDrawXCustomFunction::Mx_SendStringToExecute 执行一个带参数的命令.详细说明如下: 参数 说明 CString sCmaName 命令 ...

  3. HTML `capture` 属性

    file 类型的 <input> 除了调起系统的文件选择框外,还可通过指定 capture 属性来现场拍照或录制.配合 accept 属性,可实现更加便捷的文件获取. 比如想要录制一段视频 ...

  4. JAVA基础——Native关键字

    一:native声明 在Java中native是关键字.它一般在本地声明,异地用C和C++来实现.它的声明有几点要注意: 1)native与访问控制符前后的关系不受限制. 2)必须在返回类型之前. 3 ...

  5. TWaver MONO模板库新鲜出炉 精彩纷呈

    MONO Design在线3D建模平台网站, www.mono-design.cn,开发组的成员们已经开始紧锣密鼓的对这个平台进行内测.在之前的文章里,我们提到用户可以获得多种多样的TWaver官方模 ...

  6. 我已经迷失在事件环(event-loop)中了【Nodejs篇】

    我第一次看到他事件环(event-loop)的时候,我是一脸懵,这是什么鬼,是什么循环吗,为什么event还要loop,不是都是一次性的吗? 浏览器中和nodejs环境中的事件环是有一些区别的,这里我 ...

  7. 洛谷——P1229 遍历问题

    P1229 遍历问题 题目描述 我们都很熟悉二叉树的前序.中序.后序遍历,在数据结构中常提出这样的问题:已知一棵二叉树的前序和中序遍历,求它的后序遍历,相应的,已知一棵二叉树的后序遍历和中序遍历序列你 ...

  8. Gym - 101670G Ice cream samples(CTU Open Contest 2017 尺取法)

    题目: To encourage visitors active movement among the attractions, a circular path with ice cream stan ...

  9. on绑定事件支持的事件类型

    blurfocusfocusinfocusoutloadresizescrollunloadclickdblclickmousedownmouseupmousemovemouseovermouseou ...

  10. RequestMapping_Ant 路径

    [使用@RequestMapping映射请求] [Ant风格资源地址支持3种匹配符] (1)? :匹配文件名中的一个字符. (2) * :匹配文件名中的任意字符. (3) ** :**匹配多层路径. ...