다른 개체에 대한 접근을 제어하기 위해 대리자를 제공
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

객체에서 프록시가 될려면
- 서버와 프록시는 같은 인터페이스를 사용해야 한다.
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 - 실제 객체 호출
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 - 프록시 호출
See Also
- 동적 Proxy