설계패턴 11. Adapter Pattern

LSDrug·2024년 6월 10일

설계패턴(完)

목록 보기
11/26

이번에 배워볼 것은 Adapter Pattern이다.


1. 정의

해당 패턴은 다음과 같이 정의한다.

  • 하나의 인터페이스를 다른 인터페이스로 전환하는 역할을 하는 패턴
  • 이미 제공되어 있는 것필요한 것 사이의 차이를 없애 주는 디자인 패턴을 말한다.

쉽게 말해서 교류 110볼트를 220볼트로 변경해주는 어댑터와 같은 효과를 발휘하는 패턴이라고 할 수 있다.

Wrapper는 '감싸는 것'이라는 의미가 있는데, 무엇인가를 포장해서 다른 용도로 사용할 수 있게 교환해주는 것이라고 할 수 있다.

따라서 Adapter PatternWrapper Pattern이라고도 불린다.


2. 종류

해당 패턴은 두 가지의 종류가 있다.

  • 클래스에 의한 Adapter 패턴(상속)
  • 인스턴스에 의한 Adapter 패턴(위임)

3. 예시

목적: Banner 클래스를 사용해서 Print 인터페이스를 충족시키는 클래스를 만들자.

다음 목적에 따라 다음을 생각해 볼 수 있다.

class Banner:
    def __init__(self, word):
        self.word = word

    def showWithParen(self):
        print("(" + self.word + ")")

    def showWithAster(self):
        print("*" + self.word + "*")


class Print:
    def printWeak(self):
        pass

    def printStrong(self):
        pass


class PrintBanner(Banner, Print):  # 상속
    def __init__(self, word):
        # 명확성을 위해 super()를 사용하여 부모 클래스의 생성자 호출
        super(PrintBanner, self).__init__(word) 

    def printWeak(self):
        self.showWithParen()

    def printStrong(self):
        self.showWithAster()


# 클라이언트 코드
pb = PrintBanner("hello")
pb.printStrong()  # *hello* 출력
pb.printWeak()   # (hello) 출력
class Banner:
    def __init__(self, word):
        self.word = word

    def showWithParen(self):
        print("(" + self.word + ")")

    def showWithAster(self):
        print("*" + self.word + "*")

class Print:
    def printWeak(self):
        pass

    def printStrong(self):
        pass

class PrintBanner(Print):  # 위임의 경우
    def __init__(self, word):
        self.banner = Banner(word) # Banner 객체를 인스턴스 변수로 가짐

    def printWeak(self):
        self.banner.showWithParen()

    def printStrong(self):
        self.banner.showWithAster()


# 클라이언트 코드
pb = PrintBanner("hello")
pb.printStrong()  # *hello* 출력
pb.printWeak()   # (hello) 출력

4. 특징

  • Adapter Pattern은 맞지 않는 기존의 인터페이스를 현재 코드에 맞게 변환시켜주는 역할을 한다.
profile
마약같은 코딩, 마약같은 코딩러

0개의 댓글