我正在查看解释代理模式的代码示例。这是代码:
/**
* 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();
}
}
/**
* 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
}
}
/**
* 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
}
}
假设代理模式正确实现,这是程序的主要方法。这是我想知道的:代码中的注释说,当我们使用代理图像对象时,如果我们将图片加载到内存中,则仅加载该图像。但是如果我们不使用代理,直接创建真实图像,当我们加载这个类的一个实例时,我们会将这个类的所有实例加载到内存中。我不明白为什么会这样。是的,代理模式的重点就是这样做,但我不明白为什么当我们调用 highResolutionImageNoProxy2.showImage(); 时所有 3 个 highResolutionImageNoProxy 对象都加载到内存中;. 任何人都可以解释一下吗?
谢谢
编辑:我想我知道为什么了。因为ImageProxy类只有在尝试对对象进行操作时才会调用HighResolutionImage类的构造函数,但是如果我们直接创建一个HighResolutionImage,那么由于它的构造函数创建了对象,所以所有的对象都被加载到内存中。