[디자인 패턴] 프록시 패턴 (Proxy Pattern)

oy Hong·2024년 4월 13일

기술

목록 보기
16/23

프록시 패턴 (Proxy Pattern)

클라이언트 코드를 변경하지 않고 기존 클래스의 객체에 몇 가지 추가 행동들을 추가해야 할 때 매우 유용한 구조 디자인 패턴이다.

  • 객체 사용시 객체를 직접 호출하는게 아닌 프록시 클래스를 부르게 되고 프록시는 실제 역할을 하는 클래스에게 처리를 요구한다.

Proxy : 대리인, 대리권, 대리


특징

프록시들은 모든 실제 작업을 다른 객체에 위임한다. 각 프록시 메서드는 프록시가 서비스 객체의 자식 클래스가 아닌 이상 최종적으로 서비스 객체를 참조해야 한다.


장단점

장점

  • 실제 일을 하는 클래스와 구분 지을 수 있음
  • 사이즈가 큰 객체가 있을 시 로딩 전에 프록시 객체를 통해 참조 가능

단점

  • 로직이 복잡해지면서 코드 읽기가 좋지 않다.

코드 예시

	public interface ISubject
    {
        void Request();
    }

    class RealSubject : ISubject
    {
        public void Request()
        {
            Console.WriteLine("RealSubject: Handling Request.");
        }
    }

    class Proxy : ISubject
    {
        private RealSubject _realSubject;
        
        public Proxy(RealSubject realSubject)
        {
            this._realSubject = realSubject;
        }

        public void Request()
        {
        	// 추가 행동들을 추가한다.
            if (this.CheckAccess())
            {
                this._realSubject.Request();

                this.LogAccess();
            }
        }
        
        public bool CheckAccess()
        {
            Console.WriteLine("Proxy: Checking access prior to firing a real request.");

            return true;
        }
        
        public void LogAccess()
        {
            Console.WriteLine("Proxy: Logging the time of request.");
        }
    }
    
    public class Client
    {
        public void ClientCode(ISubject subject)
        {
            // ...
            
            subject.Request();
            
            // ...
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Client client = new Client();
            
            Console.WriteLine("Client: Executing the client code with a real subject:");
            RealSubject realSubject = new RealSubject();
            client.ClientCode(realSubject);

            Console.WriteLine();

            Console.WriteLine("Client: Executing the same client code with a proxy:");
            Proxy proxy = new Proxy(realSubject);
            client.ClientCode(proxy);
        }
    }

출력
Client: Executing the client code with a real subject:
RealSubject: Handling Request.

Client: Executing the same client code with a proxy:
Proxy: Checking access prior to firing a real request.
RealSubject: Handling Request.
Proxy: Logging the time of request.

0개의 댓글