스프링 핵심 원리 - 고급편을 학습하며 정리한 내용입니다.
접근 제어
부가 기능 추가
둘 다 프록시를 사용하지만, 의도에 따라 구분된다.
프록시 패턴 : 접근 제어가 목적
데코레이터 패턴 : 새로운 기능 추가가 목적
접근 제한
강의에서 제공되는 코드의 일부입니다.
public class ProxyPatternClient {
private final Subject subject;
public ProxyPatternClient(Subject subject) {
this.subject = subject;
}
public void execute(){
subject.operation();
}
}
@Slf4j
public class CacheProxy implements Subject{
private final 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;
}
}
@Test
void cacheProxyTest(){
RealSubject realSubject = new RealSubject();
CacheProxy cacheProxy = new CacheProxy(realSubject);
ProxyPatternClient client = new ProxyPatternClient(cacheProxy);
client.execute(); // realSubject 호출
client.execute(); // cacheProxy에서 즉시 반환 -> 시간 단축
client.execute();
}