프록시 패턴 (Proxy Pattern)

구교석·2024년 3월 23일
post-thumbnail

프록시 패턴 (Proxy Pattern) 은 구조 패턴 중 하나로 이는 소프트웨어에서 특정한 문제를 해결하기 위해 반복적으로 발생하는 구조를 식별하고, 그 구조에 따라 일반화된 해결책을 제시하는 것을 의미합니다.
한마디로 일괄적으로 관리할 수 있도록 만드는 패턴입니다.

프록시 패턴이란?

프록시 패턴(Proxy Pattern)은 대상 원본 객체를 대리하여 대신 처리하게 함으로써 로직의 흐름을 제어하는 행동 패턴이다.
프록시(Proxy)의 사전적인 의미는 '대리인'이라는 뜻이다. 즉, 누군가에게 어떤 일을 대신 시키는 것을 의미하는데, 이를 객체 지향 프로그래밍에 접목해보면 클라이언트가 대상 객체를 직접 쓰는게 아니라 중간에 프록시(대리인)을 거쳐서 쓰는 코드 패턴이라고 보면 된다. 따라서 대상 객체(Subject)의 메소드를 직접 실행하는 것이 아닌, 대상 객체에 접근하기 전에 프록시(Proxy) 객체의 메서드를 접근한 후 추가적인 로직을 처리한뒤 접근하게 된다.

프록시 패턴 구조

ServieInterface

Proxy와 RealSubject를 하나로 묶는 인터페이스 (다형성)
대상 객체와 프록시 역할을 동일하게 하는 추상 메소드 operation() 를 정의한다.
인터페이스가 있기 때문에 클라이언트는 Proxy 역할과 RealSubject 역할의 차이를 의식할 필요가 없다.

Server

원본 대상 객체

Proxy

대상 객체(RealSubject)를 중계할 대리자 역할
프록시는 대상 객체를 합성(composition)한다.
프록시는 대상 객체와 같은 이름의 메서드를 호출하며, 별도의 로직을 수행 할수 있다 (인터페이스 구현 메소드)
프록시는 흐름제어만 할 뿐 결과값을 조작하거나 변경시키면 안 된다.

Client

Subject 인터페이스를 이용하여 프록시 객체를 생성해 이용.
클라이언트는 프록시를 중간에 두고 프록시를 통해서 RealSubject와 데이터를 주고 받는다.

프록시 패턴 코드

기본형 프록시

interface ISubject {
    void action();
}

class RealSubject implements ISubject {
    public void action() {
        System.out.println("원본 객체 액션 !!");
    }
}
class Proxy implements ISubject {
    private RealSubject subject; // 대상 객체를 composition

    Proxy(RealSubject subject) {
        this.subject = subject;
    }

    public void action() {
        subject.action(); // 위임
        /* do something */
        System.out.println("프록시 객체 액션 !!");
    }
}

class Client {
    public static void main(String[] args) {
        ISubject sub = new Proxy(new RealSubject());
        sub.action();
    }
}

가상 프록시

class Proxy implements ISubject {
    private RealSubject subject; // 대상 객체를 composition

    Proxy() {
    }

    public void action() {
    	// 프록시 객체는 실제 요청(action(메소드 호출)이 들어 왔을 때 실제 객체를 생성한다.
        if(subject == null){
            subject = new RealSubject();
        }
        subject.action(); // 위임
        /* do something */
        System.out.println("프록시 객체 액션 !!");
    }
}

class Client {
    public static void main(String[] args) {
        ISubject sub = new Proxy();
        sub.action();
    }
}

보호 프록시

class Proxy implements ISubject {
    private RealSubject subject; // 대상 객체를 composition
    boolean access; // 접근 권한

    Proxy(RealSubject subject, boolean access) {
        this.subject = subject;
        this.access = access;
    }

    public void action() {
        if(access) {
            subject.action(); // 위임
            /* do something */
            System.out.println("프록시 객체 액션 !!");
        }
    }
}

class Client {
    public static void main(String[] args) {
        ISubject sub = new Proxy(new RealSubject(), false);
        sub.action();
    }
}

로깅 프록시

class Proxy implements ISubject {
    private RealSubject subject; // 대상 객체를 composition

    Proxy(RealSubject subject {
        this.subject = subject;
    }

    public void action() {
        System.out.println("로깅..................");
        
        subject.action(); // 위임
        /* do something */
        System.out.println("프록시 객체 액션 !!");

        System.out.println("로깅..................");
    }
}

class Client {
    public static void main(String[] args) {
        ISubject sub = new Proxy(new RealSubject());
        sub.action();
    }
}

참고 사이트


프록시 패턴
[Design Pattern] 프록시 패턴(Proxy Pattern) 알아보기
출처: https://dev-coco.tistory.com/177 [슬기로운 개발생활:티스토리]

[Java] 프록시 패턴(Proxy Pattern)이란? - 개념 및 예제
출처: https://ittrue.tistory.com/555 [IT is True:티스토리]

profile
끊임없이 노력하는 개발자

0개의 댓글