[디자인 패턴] Proxy

orca·2024년 9월 29일

CS

목록 보기
25/46
post-thumbnail

proxy 패턴은 실제 객체를 직접 참조하는 대신 프록시를 통해 객체에 대한 요청을 처리하는 패턴입니다.

Proxy 패턴

  • 실제 객체를 직접 참조하는 대신 프록시를 통해 객체에 대한 요청을 처리함

주요 용도

  • Remote Proxy: 원격 서버에 있는 객체에 대한 로컬 처리를 제공
  • Virtual Proxy: 생성 비용이 높은 객체의 생성을 지연함. 객체가 실제로 필요할 때까지 객체의 생성을 미루고, 필요할 때 객체를 생성함
  • Protection Proxy: 용자의 권한에 따라 객체의 특정 메소드 접근을 제한함

example

사용자가 실제로 이미지를 보기 전까지 이미지 로딩을 지연시키는 간단한 이미지 뷰어 애플리케이션

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();
    }
}
  • ImageProxyHighResolutionImage 객체 생성을 담당함
  • ImageProxydisplayImage() 가 처음 호출 될 때 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 가 클라이언트 요청을 대신 처리

0개의 댓글