ABOUT ME

설명이 필요해?

Today
Yesterday
Total
  • [Design pattern] Adapter 패턴
    IT/Design pattern 2023. 1. 22. 19:53
    SMALL

    Adapter 패턴이란?

     

    GoF 책 에서는 이렇게 설명하고 있다

    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

    한 클래스의 인터페이스를 클라이언트가 기대하는 다른 인터페이스로 변경한다. Adapter 패턴은 호환되지 않는 인터페이스로인해 다른 방법으로는 불가능 했던 클래스가 함께 동작하도록 할 수 있다.

    어댑터 클래스 다이어그램

     

     

    Adapter 패턴에는 크게 두가지가 있다.

    1. 객체 어댑터

    • Target 인터페이스를 구현하기위해 Adaptee 클래스의 인스턴스에서 구체적인 메서드를 호출하는 방식

    2. 클래스 어댑터

    • 다중상속을 이용하여 Target 인터페이스와 Adaptee 를 동시에 재정의 또는 구현하는 방식

     

    어떻게 활용하면 좋을까?

    1. 외부 라이브러리 또는 변경하기 쉽지 않은 코드의 인터페이스가 현재 사용중인것과 일치하지 않을 때 사용할 수 있다.

     

    예제

    Animal interface 를 구현한 Cat class 가 있는데 Human class 와는 호환되지 않는다. 이때 Human class를 Animal interface 와 동일한 인터페이스로 동작할 수 있도록 한다.

     

    IAnimal interface

    abstract class IAnimal {
      /// 걷기
      void walk();
    
      /// 울부짖기
      void growl();
    }

     

    Cat class

    class Cat implements IAnimal {
      @override
      void growl() {
        print('야옹~~~~');
      }
    
      @override
      void walk() {
        print('슈슈슉~~~');
      }
    }

     

    Human class

    class Human {
      void walk() {
        print('저벅저벅');
      }
    
      void say() {
        print('하이~~');
      }
    }
    

     

    HumanAdapter class

    class HumanAdapter implements IAnimal {
      final Human human;
      HumanAdapter({required this.human});
    
      @override
      void growl() {
        human.say();
      }
    
      @override
      void walk() {
        human.walk();
      }
    }

     

    실행

    void main(List<String> arguments) {
      IAnimal cat = Cat();
      IAnimal human = HumanAdapter(human: Human());
    
      cat.growl();
      cat.walk();
    
      human.growl();
      human.walk();
    }
    
    
    결과
    
    /Users/satoshi/fvm/versions/3.3.9/bin/cache/dart-sdk/bin/dart --enable-asserts /Users/satoshi/Documents/aaa/bin/aaa.dart
    야옹~~~~
    슈슈슉~~~
    하이~~
    저벅저벅
    
    Process finished with exit code 0

     

    이와같이 Human 클래스가 Adapter에 들어가면서 Animal 인터페이스처럼 동작하는것을 확인할 수 있다.

    LIST

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

    [Design pattern] Proxy 패턴  (0) 2023.01.24
Designed by Tistory.