특정 객체에 대한 접근을 제어하거나 기능을 추가할 수 있는 패턴이다.
요청을 proxy라는 대리인을 거쳐서 쓰는 패턴이다 = 초기화 지연, 접근 제어, 로깅, 캐싱, 액세스 권한 확인 등 사용 가능 → 성능 향상
- 클라이언트 → realSubject (X)
- 클라이언트 → Proxy → realSubject (O)
기존에 생성된 class 코드를 변경하지 않고 사용 하는 방법
기존에 작성된 GameService의 startGame()의 실행시간까지 알고 싶을 때
GameService를 상속받은 GameServiceProxy를 생성 (재정의 하여 사용)
public class GameService {
public void startGame() {
System.out.println("이 자리에 오신 여러분을 진심으로 환영합니다");
}
}
public class GameServiceProxy extends GameService {
@Override
public void startGame() {
long before = System.currentTimeMillis();
super.startGame();
System.out.println(System.currentTimeMillis() - before); // 실행 시간
}
public class Client {
public static void main(String[] args) {
//GameService gameService = new GameService();
GameService gameService = new GameServiceProxy();
gameService.startGame();
}
}
class가 아닌 interface로 만들기
- 테스트 코드를 만드는 등, 더 유연하다
- 클라이언트가 GameServiceProxy를 거쳐서 DefaultGameSerivce를 사용 (client → proxy → realSubject)
public interface GameService {
public void startGame();
}
public class DefaultGameService implements GameService {
@Override
public void startGame() {
System.out.println("이 자리에 오신 여러분을 진심으로 환영합니다");
}
}
///////////////////////
public class GameServiceProxy implements GameService {
private GameService gameService; // subject type 의 필드를 가지고 있어야하고
public GameServiceProxy(GameService gameService) { // 타겟에 대항하는 것을 주입 받아서
this.gameService = gameService;
}
@Override
public void startGame() {
long before = System.currentTimeMillis();
gameService.startGame();
System.out.println(System.currentTimeMillis() - before);
}
}
public class Client {
public static void main(String[] args) {
GameService gameService = new GameServiceProxy(new DefaultGameService());
gameService.startGame();
}
}
Lazy Initialization
주입 받을 필요 없이 gameService 에서 바로 GameServiceProxy를 쓰면 되는 것임
public class GameServiceProxy implements GameService {
private GameService gameService;
@Override
public void startGame() {
long before = System.currentTimeMillis();
if (this.gameService == null) {
this.gameService = new DefaultGameService();
}
gameService.startGame();
System.out.println(System.currentTimeMillis() - before);
}
}
public class Client {
public static void main(String[] args) {
GameService gameService = new GameServiceProxy();
gameService.startGame();
}
}
ProxyPattern의 장점과 단점
장점
- 기존 코드를 변경하지 않고 새로운 기능을 추가할 수 있다 (OCP)
- 기존 코드가 해야 하는 일만 유지할 수 있다(SRP)
- 기능 추가 및 초기화 지연 등으로 다양하게 활용할 수 있다
단점
- 코드의 복잡도가 증가한다 = 가독성이 떨어진다
[출처]
'𝑷𝒓𝒐𝒈𝒓𝒂𝒎𝒎𝒊𝒏𝒈 > 𝐽𝐴𝑉𝐴' 카테고리의 다른 글
[JAVA] Collection - List (LinkedList) (0) | 2022.11.21 |
---|---|
[JAVA] Collection - List (ArrayList) (0) | 2022.11.21 |
[디자인패턴] 싱글톤(Singleton) 패턴 (0) | 2022.11.19 |
[JAVA] Thread (스레드) (0) | 2022.11.02 |
[JAVA] 자바 queue (큐) 클래스 (0) | 2022.02.13 |