HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
객체 지향 프로그래밍
객체 지향 프로그래밍
/
디자인 패턴
디자인 패턴
/
Proxy Pattern
Proxy Pattern
Proxy Pattern

Proxy Pattern

💡
다른 개체에 대한 접근을 제어하기 위해 대리자를 제공

Intent

Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object.
A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.
 
직접 호출
직접 호출
대리자
대리자

프록시의 Applicablity

❗
프록시 ≠ 프록시 패턴
  • 접근 제어 → 프록시 패턴
    • 권한에 따른 접근 차단
    • 캐싱
    • 지연 로딩
  • 부가 기능 추가 → 데코레이터 패턴
    • 요청 값이나, 응답 값을 중간에 변형
    • 실행 시간 측정, 로깅
    • 트랜잭션 처리

Implementation

notion image
 
객체에서 프록시가 될려면
  1. 서버와 프록시는 같은 인터페이스를 사용해야 한다.
 
Code Example
public interface Subject { String operation(); }
import lombok.extern.slf4j.Slf4j; @Slf4j public class RealSubject implements Subject { @Override public String operation() { log.info("실제 객체 호출"); sleep(1000); return "data"; } private void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
import lombok.extern.slf4j.Slf4j; @Slf4j public class CacheProxy implements Subject{ private Subject target; private String cacheValue; public CacheProxy(Subject target) { this.target = target; } @Override public String operation() { log.info("프록시 호출"); if(cacheValue == null){ cacheValue = target.operation(); } return cacheValue; } }
 
public class ProxyPatternClient { private Subject subject; public ProxyPatternClient(Subject subject) { this.subject = subject; } public void execute(){ subject.operation(); } }
  • Subject (Target)를 필드로 하나 가지고 있다.
 
import org.junit.jupiter.api.Test; class ProxyPatternTest { @Test void noProxyTest(){ RealSubject realSubject = new RealSubject(); ProxyPatternClient client = new ProxyPatternClient(realSubject); client.execute(); client.execute(); client.execute(); } @Test void proxytest(){ RealSubject target = new RealSubject(); CacheProxy cacheProxy = new CacheProxy(target); ProxyPatternClient client = new ProxyPatternClient(cacheProxy); client.execute(); client.execute(); client.execute(); } }
  • 실행 결과
00:49:24.021 [main] INFO RealSubject - 실제 객체 호출 00:49:25.025 [main] INFO RealSubject - 실제 객체 호출 00:49:26.067 [main] INFO RealSubject - 실제 객체 호출
noProxy - 3초
00:49:22.918 [main] INFO CacheProxy - 프록시 호출 00:49:22.935 [main] INFO RealSubject - 실제 객체 호출 00:49:23.978 [main] INFO CacheProxy - 프록시 호출 00:49:23.979 [main] INFO CacheProxy - 프록시 호출
proxy - 1초
 
 

See Also

  • 동적 Proxy