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

업데이트:

카테고리:

태그:


어댑터 패턴이란?

어댑터 패턴은 구조 패턴 중의 하나로 이름 그대로 어댑터처럼 호환성이 없는 클래스들의 인터페이스를 다른 클래스가 이용할 수 있도록 변환해주는 패턴이다.

장점

  • 코드의 재사용성을 높일 수 있다.

구성

image

이미지 출처 : https://en.wikipedia.org/wiki/Adapter_pattern

  • Client : 외부 라이브러리나 시스템을 사용하려는 객체
  • Target : Adapter가 구현하려는 인터페이스
  • Adaptee : 외부 라이브러리, 외부 시스템 객체
  • Adapter : Adaptee와 Client의 중간에서 둘을 연결시켜주는 연결자 Target의 인터페이스를 구현한다.

Client는 Target의 인터페이스를 이용해 Adapter에 요청을 보낸다. Adapter는 받은 요청을 Adaptee가 이해할 수 있도록 통역(변환)하고, 요청에 대한 처리는 Adaptee에서 이루어 진다.

예시 (Kotlin)

위의 다이어그램과 같이 클래스를 생성해보자

우선 Client가 다룰 수 있는 인터페이스를 가지고 있는 Target이 있을 것이다. 후에 Adapter가 상속을 받아야 하므로 open클래스로 생성하였다.

open class Target{
    open fun operation(){
        println("Target Operation")
    }
}

그리고 Target을 통해 specificOperation()을 사용하고 싶은 Client가 있을 것이다.

class Client{
    fun operation(target : Target){
        target.operation()
    }
}

그리고 specificOperation()을 가지고 있는 객체 Adaptee가 존재한다.

class Adaptee{
    fun specificOperation(){
        println("Specific Operation")
    }
}

Client는 Adaptee를 이용해 specificOperation()을 사용하고 싶지만 Client가 할 수 있는 것은 Target을 이용한 operation()뿐이다. 이때 Client가 specificOperation()을 사용할 수 있도록 중간 다리 또는 통역을 해줄 Adapter가 필요하다.

class Adapter( private val adaptee: Adaptee ) : Target() { override fun operation(){ adaptee.specificOperation() } }

Adapter는 Target을 상속받아 당연하게도 Client가 사용이 가능하고 Target으로부터 상속받은 operation()에서 adaptee의 specificOperation()을 사용하는 것으로 Target의 동작 방식 그대로 specificOperation()을 사용할 수 있게 해준다.

fun main(){
    val adaptee  = Adaptee()
    Client().operation(Adapter(adaptee))
}


출력

Specific Operation