PHpullh
학습 라이브러리/Kotlin/어댑터 패턴 (Adapter Pattern)

KOTLIN · 객체지향

어댑터 패턴 (Adapter Pattern)

호환되지 않는 인터페이스를 연결하는 패턴입니다. 확장 함수로도 간결한 어댑터를 구현할 수 있습니다.

객체지향중급adapterextension-functioninterface-conversionlegacy

핵심 설명

호환되지 않는 인터페이스를 연결하는 패턴입니다. 확장 함수로도 간결한 어댑터를 구현할 수 있습니다.

Kotlin code

// 레거시 시스템
class LegacyPrinter {
    fun printDocument(text: String, copies: Int) {
        repeat(copies) { println("[레거시] $text") }
    }
}

// 새 인터페이스
interface ModernPrinter {
    fun print(document: Document)
}

data class Document(val content: String, val copies: Int = 1)

// 클래스 어댑터
class PrinterAdapter(private val legacy: LegacyPrinter) : ModernPrinter {
    override fun print(document: Document) {
        legacy.printDocument(document.content, document.copies)
    }
}

// 확장 함수 어댑터
fun LegacyPrinter.toModern(): ModernPrinter = object : ModernPrinter {
    override fun print(document: Document) {
        printDocument(document.content, document.copies)
    }
}

fun main() {
    val legacy = LegacyPrinter()
    val modern: ModernPrinter = legacy.toModern()
    modern.print(Document("보고서 출력", 2))
}

학습 팁

확장 함수를 사용한 어댑터는 원본 클래스 수정 없이 변환 메서드를 추가할 수 있어 깔끔합니다.

주의할 점

어댑터가 너무 많아지면 간접 레이어가 복잡해집니다. 가능하면 인터페이스를 통일하는 리팩토링을 우선 고려하세요.

자주 묻는 질문

어댑터 패턴 (Adapter Pattern)란 무엇인가요?

호환되지 않는 인터페이스를 연결하는 패턴입니다. 확장 함수로도 간결한 어댑터를 구현할 수 있습니다.

어댑터 패턴 (Adapter Pattern) 학습 시 주의할 점은 무엇인가요?

어댑터가 너무 많아지면 간접 레이어가 복잡해집니다. 가능하면 인터페이스를 통일하는 리팩토링을 우선 고려하세요.