실제 객체에 대한 접근을 제어하거나 추가적인 기능(예: 권한 체크, 로깅 등)을 수행하기 위해 실제 객체의 대리인 역할을 하는 객체를 사용하는 구조
1. 프록시 패턴?
- 프록시 패턴(Proxy Pattern)은 구조적 디자인 패턴 중 하나로, 대상 객체에 대한 접근을 제어하거나, 대상 객체의 행동을 대리하는 객체(프록시 객체)를 사용하여, 실제 객체를 직접 사용하지 않고 대신 동작을 수행하게 만드는 패턴이다.
- 프록시 객체는 실제 객체에 대한 "대리인" 역할을 하며, 클라이언트는 프록시 객체를 통해 실제 객체와 상호작용한다.
2. 주요 목적
- 접근 제어: 클라이언트가 직접 실제 객체에 접근할 수 없도록 제한하거나, 접근을 제어하는 기능을 제공
- 지연 초기화(Lazy Initialization): 실제 객체가 필요할 때까지 생성하지 않고, 실제 객체를 사용하는 시점에서만 초기화 가능
- 성능 최적화: 불필요한 작업을 미루거나, 캐싱 등을 통해 성능 최적화
- 로깅/모니터링: 실제 객체의 동작을 가로채서 로깅, 성능 측정, 보안 체크 등 가능
3. 종류
- 가상 프록시(Virtual Proxy): 실제 객체의 생성 비용이 크거나 시간이 많이 걸리는 경우, 실제 객체를 요청할 때까지 생성하지 않고 요청 시에 초기화하는 방식
- 보호 프록시(Protection Proxy): 접근 제어를 제공하는 프록시로, 클라이언트가 실제 객체에 접근하기 전에 특정 권한을 체크하거나 조건을 만족하는지 확인
- 리모트 프록시(Remote Proxy): 네트워크를 통해 다른 JVM 또는 다른 시스템에 위치한 객체에 접근할 때 사용. 클라이언트는 로컬 객체처럼 접근하지만, 실제 객체는 원격에 존재
- 지능형 프록시(Smart Proxy): 객체에 대한 추가적인 기능을 제공하는 프록시로, 예를 들어 참조 카운팅, 객체의 상태 관리 등 가능
4. 예시
public abstract class Animal {
public abstract String getName();
}
package ch01;
public class Cat extends Animal {
private String name = "고양이";
public String getName() {
return name;
}
}
public class Mouse extends Animal{
private String name = "쥐";
public String getName() {
return name;
}
}
public class Doorman {
public void 쫓아내(Animal animal) {
System.out.println(animal.getName() + " 쫓아내");
}
}
public class App {
public static void main(String[] args) {
Doorman doorman = new Doorman();
Mouse mouse = new Mouse();
Cat cat = new Cat();
doorman.쫓아내(cat);
doorman.쫓아내(mouse);
}
}
Proxy 패턴을 적용하여 쫓아내기전에 인사를 해보자
public class DoormanProxy {
private Doorman doorman;
public DoormanProxy(Doorman doorman) {
this.doorman = doorman;
}
public void 쫓아내(Animal animal) {
hello();
doorman.쫓아내(animal);
}
private void hello(){
System.out.println("hello");
}
}
public class App {
public static void main(String[] args) {
Doorman doorman = new Doorman();
DoormanProxy proxy = new DoormanProxy(doorman);
Mouse mouse = new Mouse();
Cat cat = new Cat();
proxy.쫓아내(cat);
proxy.쫓아내(mouse);
}
}
hello
고양이 쫓아내
hello
쥐 쫓아내
Share article