[디자인 패턴] 어댑터 패턴 (Adapter Pattern)

oy Hong·2024년 4월 14일

기술

목록 보기
19/23

어댑터 패턴 (Adapter Pattern)

호환되지 않는 객체들이 협업할 수 있도록 해주는 구조 디자인 패턴이다. 어댑터는 두 객체 사이의 래퍼 역할을 한다.


Adapter 를 사용하는 경우

  • 이미 존재하고 있는 또는 버그가 적은 클래스를 부품으로서 재사용
  • 이미 만들어진 클래스를 새로운 인터페이스에 맞게 개조시킬 때

코드 예시

	public interface ITarget
    {
        string GetRequest();
    }
    
    class Adaptee
    {
        public string GetSpecificRequest()
        {
            return "Specific request.";
        }
    }
    
    class Adapter : ITarget
    {
        private readonly Adaptee _adaptee;

        public Adapter(Adaptee adaptee)
        {
            this._adaptee = adaptee;
        }

		// 래핑 (rapping)
        public string GetRequest()
        {
            return $"This is '{this._adaptee.GetSpecificRequest()}'";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Adaptee adaptee = new Adaptee();
            ITarget target = new Adapter(adaptee);

            Console.WriteLine("Adaptee interface is incompatible with the client.");
            Console.WriteLine("But with adapter client can call it's method.");

            Console.WriteLine(target.GetRequest());
        }
    }

출력
Adaptee interface is incompatible with the client.
But with adapter client can call it's method.
This is 'Specific request.'

0개의 댓글