본문 바로가기

강의/Design pattern

프록시(Proxy) 패턴

SMALL

Proxy

클라이언트가 특정 객체의 오퍼레이션에 접근하기 전 Proxy를 지나서 접근하는 패턴
맨 처음 요청을 모두 Proxy가 받게 된다. Proxy 객체를 생성해서 접근제어 및 만드는 데 리소스가 많이 필요한 객체에 대해서 효과를 볼 수 있다.
초기화 지연, 로깅이나 캐싱 또한 가능하다.


Example Code

public class GameService {
  public void startGame() {
    System.out.println("text");
  }
}

Example Code - 2

1. 기존 코드 유지

GameServiceProxy

  public class GameServiceProxy extends GameService {
    @Override
    public void startGame() {
      long before = System.currentTimeMillis();
      super.startGame();
      System.out.println(System.currentTimeMillis() - before);
    }
  }

Client

public class Client {
  public static void main(String[] args) throws InterruptedException {
    GameService gameService = new GameServiceProxy();
    gameService.startGame();
  }
}

2. 기존 코드 변경

DefaultGameService

public class DefaultGameService implements GameService {
  @Override
  public void startGame() {
    System.out.println("text");
  }
}

GameServiceProxy

Decorator와 같이 변수를 선언해준다.

  public class GameServiceProxy extends GameService {
    private GameService gameService;
    
    @Override
    public void startGame() {
      long before = System.currentTimeMillis();
      if(this.gameService == null) {
        this.gameService = new DefaultGameService();
      }
      super.startGame();
      System.out.println(System.currentTimeMillis() - before);
    }
  }

DefaultGameService

public class DefaultGameSErvice implements GameService {
  @Override
  public void startGame() {
    System.out.println("text");
  }
}

Client

public class Client {
  public static void main(String[] args) {
    GameService gameService = new GameServiceProxy(new DefaultGameSErvice());
    gameService.startGame();
  }
}

DefaultGameService는 자신의 일만 하고 다른 클래스에서 호출만 하게 된다.


장단점

장점

  • 기존코드를 변경하지 않고 새로운 기능 추가 가능
  • 기존 코드가 해야 하는 일만 유지 가능
  • 기능 추가 및 초기화 지연 등으로 다양한 활용

단점

  • 코드 복잡도 증가

Example

Dynamic Proxy

Java Reflection으로 제공되는 기능 중 하나로, 동적으로 실행될 때 Proxy 인스턴스가 생성된다.

SMALL

'강의 > Design pattern' 카테고리의 다른 글

커맨드(Command) 패턴  (0) 2022.09.22
책임 연쇄 패턴  (0) 2022.09.22
플라이웨이트 (Flyweight) 패턴  (0) 2022.08.16
퍼싸드(Facade) 패턴  (0) 2022.08.16
브릿지 (Bridge) 패턴  (0) 2022.08.16