Design Pattern/구조 패턴

Proxy pattern

 

Proxy pattern

프록시 패턴은 어떤 객체에 대한 접근을 제어하는 용도로 대리인이나 대변인에 해당하는 객체를 제공하는 패턴입니다.

 

일반적으로 프록시는 다른 무언가와 이어지는 인터페이스의 역할을 하는 클래스이다. 프록시는 어떠한 것(이를테면 네트워크 연결, 메모리 안의 커다란 객체, 파일, 또 복제할 수 없거나 수요가 많은 리소스)과도 인터페이스의 역할을 수행할 수 있다.

 

  • 기본 객체가 리소스 집약적인 경우. 자잘한 작업들은 프록시 객체가 처리하게 한다.
  • 기본 객체에 접근을 제어해야하는 경우. 프록시 객체가 권한에 따라 접근 로직을 다르게 처리하게 한다.

실제로 Spring의 AOP는 Proxy 패턴을 통해서 적용 지점을 지정하고 앞 뒤로 횡단 공통 관심사를 처리하는 하고 있습니다. 

 

프록시 패턴 장점

1. 사이즈가 큰 객체(ex : 이미지)가 로딩되기 전에도 프록시를 통해 참조를 할 수 있다.

2. 실제 객체의 public, protected 메소드들을 숨기고 인터페이스를 통해 노출시킬 수 있다. 

3. 로컬에 있지 않고 떨어져 있는 객체를 사용할 수 있다. 

4. 원래 객체의 접근에 대해서 사전처리를 할 수 있다.

 

프록시 패턴 단점

1. 객체를 생성할때 한단계를 거치게 되므로, 빈번한 객체 생성이 필요한 경우 성능이 저하될 수 있다.

2. 프록시 내부에서 객체 생성을 위해 스레드가 생성, 동기화가 구현되야 하는 경우 성능이 저하될 수 있다.

3. 로직이 난해해져 가독성이 떨어질 수 있다.

4. 인테페이스를 상속받아 구현하여 플요없는 메서드 구현에 대한 강제성을 가진다.

 

코드를 통한 이해

이해하기 쉬운 예를 한번들어보면 유튜브의 사이트를 들어가면 많은 영상들의 썸네일 이미지가 떠있고 마우스를 가져가면 프리뷰가 실행됩니다.

만약 마우스를 가져가지 않아도 모든 영상에 프리뷰를 실행시킨다고 한다면 해당 데이터를 가져오는 일이 오래걸리게 될 것 입니다. 이때문에 우선 영상 썸네일 이미지만 먼저 보여주고 마우스 이벤트에 따라서 프리뷰 데이터를 가져와 보여주는 것이죠.

 

1. Subject

public interface Thumbnail {
    void showImage();
    void showPreview();
}

 

2. RealSubject

public class RealThumbnail implements Thumbnail{
    private String thumbnailName;

    public RealThumbnail(String thumbnailName) {
        this.thumbnailName = thumbnailName;
        loadPreview();
    }

    @Override
    public void showImage() {
        System.out.println("show image " + thumbnailName);
    }

    @Override
    public void showPreview() {
        System.out.println("show preview " + thumbnailName);
    }

    public void loadPreview() {
        System.out.println("load preview " + thumbnailName);
    }
}

 

3. Proxy

public class ProxyThumbnail implements Thumbnail{
    private RealThumbnail realThumbnail;
    private String thumbnailName;

    public ProxyThumbnail(String thumbnailName) {
        this.thumbnailName = thumbnailName;
    }

    @Override
    public void showImage() {
        System.out.println("show image " + thumbnailName);
    }

    @Override
    public void showPreview() {
        if (realThumbnail == null) {
            realThumbnail = new RealThumbnail(thumbnailName);
        }
        realThumbnail.showPreview();
    }
}

 

4. 실행 & 결과

public class ProxyPatternDemo {
    public static void main(String[] args) {
        ProxyThumbnail proxyThumbnail = new ProxyThumbnail("유튜브 영상 제목 1");
        proxyThumbnail.showImage();
        System.out.println("마우스 이동 시");
        proxyThumbnail.showPreview();
    }
}

 

 

Reference

coding-factory.tistory.com/711

'Design Pattern > 구조 패턴' 카테고리의 다른 글

Facade Pattern  (0) 2021.05.04
Decorator Pattern  (0) 2021.05.04
Composite Pattern  (0) 2021.05.04
Bridge Pattern  (0) 2021.05.04
Adapter pattern  (0) 2021.05.03