proxy 패턴은 실제 객체를 직접 참조하는 대신 프록시를 통해 객체에 대한 요청을 처리하는 패턴입니다.
사용자가 실제로 이미지를 보기 전까지 이미지 로딩을 지연시키는 간단한 이미지 뷰어 애플리케이션
interface Image {
void displayImage();
}
// 실제 이미지 로드 및 표시
class HighResolutionImage implements Image {
private String imagePath;
public HighResolutionImage(String imagePath) {
this.imagePath = imagePath;
loadImage(imagePath);
}
private void loadImage(String path) {
System.out.println("Loading high-resolution image from: " + path);
// 이미지 로딩에 시간이 걸리는 것을 시뮬레이션
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("Error loading image.");
}
}
@Override
public void displayImage() {
System.out.println("Displaying: " + imagePath);
}
}
HighResolutionImage 객체를 생성하는 데 많은 비용이 듦class ImageProxy implements Image {
private HighResolutionImage highResImage;
private String imagePath;
public ImageProxy(String imagePath) {
this.imagePath = imagePath;
}
@Override
public void displayImage() {
if (highResImage == null) {
highResImage = new HighResolutionImage(imagePath);
}
highResImage.displayImage();
}
}
ImageProxy 가 HighResolutionImage 객체 생성을 담당함ImageProxy 의 displayImage() 가 처음 호출 될 때 HighResolutionImage 객체가 생성public class ImageViewer {
public static void main(String[] args) {
Image image1 = new ImageProxy("path/to/image1.jpg");
Image image2 = new ImageProxy("path/to/image2.jpg");
System.out.println("Image 1 will be displayed on demand:");
image1.displayImage(); // 실제로 필요할 때 이미지 로드
System.out.println("Image 2 will be displayed on demand:");
image2.displayImage(); // 실제로 필요할 때 이미지 로드
}
}
HighResolutionImage 가 필요하지 않을 때까지는 ImageProxy 가 클라이언트 요청을 대신 처리