dev/🧩 디자인패턴

프록시 패턴이란? (Proxy Pattern)

wugawuga 2022. 12. 18. 03:13

프록시 패턴이란?

특정 객체로의 접근을 제어하는 대리인 (특정 객체를 대변하는 객체) 제공

 

프록시 패턴을 사용하면 왜 좋아요?

실제 메소드가 호출되기 전에 전처리 기능 등
구현 객체 변경없이 추가할 수 있다

 

기존 코드

public class GameService {
    public void startGame() {
        System.out.println("게임을 시작합니다.");
    }
}

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

 

변경 후 코드

public interface GameService {
    void startGame();
}

public class DefaultGameService implements GameService {

    @Override
    public void startGame() {
        System.out.println("게임을 시작합니다.");
    }
}

public class GameServiceProxy implements GameService {

    private GameService gameService;

    @Override
    public void startGame() {
        if (this.gameService == null) {
            this.gameService = new DefaultGameService();
        }

        gameService.startGame();
    }
}

 

public class Client {

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

 

장점

이렇게 DefaultGameService 를 객체를 생성하는 것이 아닌 GameServiceProxy 대리 객체를 사용한다

위에서 말했다 싶이 기존 코드를 수정하지 않고 프록시를 통해 새로운 기능을 추가할 수 있다

 

단점

코드가 매우 어려워질 수 있다