프록시 패턴을 설명하는 코드 샘플을보고 있습니다. 여기서 코드 :프록시 패턴 - 메모리에로드 중
/**
* 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()를 호출하면 highResolutionImageNoProxy 객체가 모두 메모리에로드되는 이유를 알 수 없습니다. . 아무도 그것을 설명 할 수 있습니까?
감사
편집 : 나는 내가 이유를 알아 낸 것 같아요. ImageProxy 클래스는 객체에 대해 작업을 시도 할 때만 HighResolutionImage 클래스의 생성자를 호출하기 때문에 HighResolutionImage를 직접 생성하면 생성자가 객체를 생성하기 때문에 모든 객체가 메모리에로드됩니다.
네, 당신의 편집 예, 내가 잘 난 그냥 그것을 눈치 못했습니다 :-) –