프록시 (Proxy) 패턴
어떠한 객체를 대리하여 대신 처리하게 함으로써, 로직의 흐름을 제어하는 행동 패턴이다.
즉, 클라이언트가 대상 객체를 직접 참조하는 것이 아니라, 중간에 프록시라는 대리인을 거쳐서 접근하는 코드 패턴이다.
대상 객체의 메서드를 직접 실행하는 것이 아니라, 프록시 객체의 메서드에 접근한 후 추가적인 로직을 처리한 뒤 접근하게 된다.

프록시 패턴의 구조

`RealSubject`: 원본 대상 객체
`Proxy`: 대상 객체(RealSubject)를 중계할 대리자 역할
`Subject`: `RealSubject`와 `Proxy`를 하나로 묶는 인터페이스 (대상 객체와 프록시의 역할을 동일하게 하는 추상 메서드(operation())을 정의함)
예를 들어, 아래와 같은 여행 예약 시스템이 있다고 가정한다.
(출처: https://ittrue.tistory.com/555)
public class Reservation {
private int reservationId;
private String travelerName;
private String destination;
public Reservation(int reservationId, String travelerName, String destination) {
this.reservationId = reservationId;
this.travelerName = travelerName;
this.destination = destination;
}
public int getReservationId() {
return reservationId;
}
public String getTravelerName() {
return travelerName;
}
public String getDestination() {
return destination;
}
}
클라이언트가 접근할 `ReservationServiceSubject` 인터페이스를 생성한다. (`Subject`)
public interface ReservationServiceSubject {
void addReservation(Reservation reservation);
Reservation findReservation(int reservationId);
}
`ReservationServiceRealSubject` 클래스로 `ReservationServiceSubject` 인터페이스를 구현하여, 예약과 조회 기능을 구현한다. (`RealSubject`)
import java.util.ArrayList;
import java.util.List;
public class ReservationServiceRealSubject implements ReservationServiceSubject {
private List<Reservation> reservations = new ArrayList<>();
public void addReservation(Reservation reservation) {
reservations.add(reservation);
}
public Reservation findReservation(int reservationId) {
for (Reservation reservation : reservations) {
if (reservation.getReservationId() == reservationId) {
return reservation;
}
}
return null;
}
}
실제 서비스인 `ReservationServiceRealSubject` 클래스를 감싼 프록시 객체인 `ReservationServiceProxy` 클래스를 생성한다. (`Proxy`)
`ReservationServiceRealSubject` 객체를 가지고 있으며, 예약이나 조회를 하기 전에 특정 작업을 수행하고 realSubject의 기능을 호출하여 실제 예약과 조회를 할 수 있다.
class ReservationServiceProxy implements ReservationServiceSubject {
private ReservationServiceRealSubject reservationService = new ReservationServiceRealSubject();
public void addReservation(Reservation reservation) {
// 여행 예약을 추가하기 전에 어떤 작업을 수행할 수 있음
reservationService.addReservation(reservation);
}
public Reservation findReservation(int reservationId) {
// 여행 예약을 조회하기 전에 어떤 작업을 수행할 수 있음
return reservationService.findReservation(reservationId);
}
}
클라이언트는 `ReservationServiceProxy` 클래스로부터 객체를 생성하여, 특정 작업을 수행하고 예약하거나 조회할 수 있다.
public class ProxyMain {
public static void main(String[] args) {
ReservationServiceProxy reservationService = new ReservationServiceProxy();
// 여행 예약 추가
Reservation reservation = new Reservation(1, "홍길동", "프랑스 파리");
reservationService.addReservation(reservation);
// 여행 예약 검색
Reservation findReservation = reservationService.findReservation(1);
if (findReservation != null) {
System.out.println("예약 번호: " + findReservation.getReservationId() +
", 여행자: " + findReservation.getTravelerName() +
", 목적지: " + findReservation.getDestination());
} else {
System.out.println("예약 정보를 찾을 수 없습니다.");
}
}
}
이와 같이, 프록시 패턴을 사용하면 객체에 직접 접근하지 않고, 중간에 계층을 도입하여 여러 기능을 추가하거나 제어하면서 실제 서비스를 대신 수행하는 패턴이다.
프록시 패턴의 효과
프록시 패턴을 통해, 개방 폐쇄 원칙 (OCP)과 단일 책임 원칙 (SRP)를 지킬 수 있다.
- 개방 폐쇄 원칙 - 기존 대상 객체의 코드를 변경하지 않고 새로운 기능을 추가할 수 있다.
- 단일 책임 원칙 - 대상 객체는 자신의 기능에만 집중하고, 그 이외의 부가 기능은 프록시 객체에 위임하여 다중 책임을 회피할 수 있다.
접근을 제어하거나 기능을 추가하고 싶은데, 기존의 특정 객체를 수정할 수 없는 상황일 때 유용하다.
클라이언트는 객체를 신경쓰지 않고, 서비스 객체를 제어하거나 생명주기를 관리할 수 있다.
출처
https://ittrue.tistory.com/555
[Java] 프록시 패턴(Proxy Pattern)이란? - 개념 및 예제
프록시 패턴(Proxy Pattern) 프록시(Proxy)는 대리자, 대변인이라는 뜻을 가진 단어다. 대리자/대변인은 다른 누군가를 대신해 그 역할을 수행하는 존재를 말한다. 따라서 프록시 패턴은 특정 객체의
ittrue.tistory.com
💠 프록시(Proxy) 패턴 - 완벽 마스터하기
Proxy Pattern 프록시 패턴(Proxy Pattern)은 대상 원본 객체를 대리하여 대신 처리하게 함으로써 로직의 흐름을 제어하는 행동 패턴이다. 프록시(Proxy)의 사전적인 의미는 '대리인'이라는 뜻이다. 즉, 누
inpa.tistory.com
'CS스터디' 카테고리의 다른 글
| [디자인패턴] 팩토리 메서드 패턴, 추상 팩토리 패턴 (0) | 2024.05.06 |
|---|---|
| [Web] OAuth의 개념, OAuth의 동작 메커니즘 (1) | 2024.03.18 |
| [자료구조/알고리즘] 인덱스의 개념, 인덱스 자료구조 (해시 테이블, B+ Tree) (1) | 2024.02.26 |
| [운영체제] 프로세스와 스레드, 멀티 프로세스와 멀티 스레드 (0) | 2024.02.19 |
| [Web] Web Server와 WAS (0) | 2024.02.06 |