특정 인터페이스를 지원하지 않는 대상 객체를 인터페이스를 지원하는 Adapter에 집어넣어서 사용하는 방법
서로 일치하지 않는 인터페이스를 갖는 클래스들을 함께 동작 가능하게 만듬
⇒ 호환성 문제 해결
다음과 같은 경우 사용
⇒ 호출할려는 Adaptee의 specificOperation()
가 내부 객체로 오는지, 상속을 통해서 오는지의 차이
기존 클래스를 새로운 클래스에서 상속해서 사용 (다중 상속이 필수적)
⇒ 클래스만 래핑 가능
기존 클래스를 새로운 클래스에서 객체를 합성/구성(Compostion)해서 사용
⇒ 클래스나, 인터페이스 래핑 가능
interface Target {
fun operation()
}
open class Adaptee {
fun specificOperation() {
println("Adaptee 함수 호출")
}
}
class ClassAdapter : Target, Adaptee() {
override fun operation() {
specificOperation() // 상속받은 함수 호출
}
}
class ObjectAdapter(var adaptee: Adaptee) : Target {
override fun operation() {
adaptee.specificOperation() // 넘겨받은 객체에서 함수 호출
}
}
class Client {
var targetClassAdapter: Target = ClassAdapter()
var targetObjectAdapter: Target = ObjectAdapter(Adaptee())
fun execute() {
targetClassAdapter.operation()
targetObjectAdapter.operation()
}
}