프록시 패턴

프록시 객체는 원래 객체와 동일한 타입을 감싸고 있는 객체이다. 프록시 객체가 원래 객체를 감싸서 client의 요청을 처리하게 하는 패턴이다.

프록시 패턴을 쓰는 이유는 접근을 제어하고 싶거나, 부가 기능을 추가하고 싶을 때 사용한다.

// interface Calculator
public interface Calculator {
	public long factorial(long num);
}
// class ImpeCalculator
public class ImpeCalculator implements Calculator {

	@Override
	public long factorial(long num) {
		long result = 1;
		for (long i = 1; i <= num; ++i) result *= i;
		return result;
	}
}
// class ProxyCalculator
public class ProxyCalculator implements Calculator {

	private Calculator delegate;
	
	public ProxyCalculator(Calculator delegate) {
		this.delegate = delegate;
	}
	
	@Override
	public long factorial(long num) {
		
		long start = System.nanoTime();
		long result = delegate.factorial(num);
		long end = System.nanoTime();
		
		System.out.printf("%s.factorial(%d) 실행시간 = %d\n", delegate.getClass().getSimpleName(), num, (end - start));
		return result;
	}
}
// class Main
public class Main {

	public static void main(String[] args) {
		
		Calculator cal = new ImpeCalculator();
		Calculator proxyCal = new ProxyCalculator(cal);
		
		System.out.println(cal.factorial(5));
		System.out.println(proxyCal.factorial(5));		
	}
}
120
ImpeCalculator.factorial(5) 실행시간 = 1600
120

핵심 기능 구현 객체들의 실행시간을 파악하기 위하여 프록시 객체를 이용했다. 프록시 객체는 핵심 기능 외에 공통적인 기능을 담은 객체를 말한다. 이는 인터페이스의 구현 객체에 대한 횡단 관심사를 공통 로직화 했지만, 반대로 말하자면 인터페이스 종송적이기에 인터페이스끼리 중복코드가 발생할 수 있다. (Logging, Security 등)

Spring 에서는 이를 처리하기 위해 Runtime 시, 동적으로 프록시 객체를 만들어주며 이것을 AOP 라고 한다.


참고

  • https://velog.io/@max9106/Spring-%ED%94%84%EB%A1%9D%EC%8B%9C-AOP-xwk5zy57ee
  • https://pangtrue.tistory.com/80