컴퓨터공학

[디자인패턴] 어댑터(Adapter) 패턴에 대한 이해

TaeGyeong Lee 2023. 8. 9. 17:21

 

개요

어댑터 패턴은 존재하는 클래스의 인스턴스가 다른 인스턴스로 사용가능하도록 설계하는 디자인 패턴입니다. 한국 여행객이 일본에 와서 한국산 충전기 220v를 사용하기 위해 110v로 변환하는 젠더를 사용하는데, 이 때 어댑터의 역할이 젠더의 역할과 동일합니다.

주로 제 3자가 제공하는 프로그램의 일부를 자신의 프로그램에 적용하여 사용하고자 할 때, 어댑터 디자인 패턴을 활용할 수 있습니다.

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=aeao1208&logNo=221377980389

 

구현

예를 들어 보겠습니다. 회사 A는 애플 주식을 사는 메소드를 가진 클래스를 아래와 같이 작성했습니다.

interface stock {
    fun buy(stockName : String)
}

class appleStock: stock {
    override fun buy(stockName : String){
        println("Buy Apple Stock")
    }
}

 

회사 A는 모종의 이유로 회사 B에서 일하는 개발자 이태경에게 쿠팡 주식을 사는 메소드를 가진 클래스 작성을 요청했습니다. 이태경은 회사 A의 요청에 따라 아래와 같이 클래스(Adaptee)를 작성했습니다.

class coupangStock {
    fun buy(stockCode : String){
        println("Buy Counpang Stock")
    }
}

그런데,,, 초짜 개발자 이태경은 회사 A의 요구를 명확히 따르지 않은 채 코드를 작성했습니다. 심지어 파라미터 명을 지 마음대로 stockCode로 명명하였습니다.

회사 A의 담당자는 한숨을 쉬며 어댑터 패턴을 적용하기로 하였습니다. 어댑터 클래스를 아래와 같이 작성했습니다.

어댑터 패턴은 기존 프로그램을 Adaptee에 맞게 변형시키는 Adapter를 설계하는 패턴입니다. 회사 A 내부에서 설계한 프로그램이 초짜 개발자 이태경이 작성한 코드에서 정상적으로 실행될 수 있도록 만들어 주는 것입니다.

class stockAdapter(private val coupangStock: coupangStock) : stock {
    override fun buy(stockName : String){
        val CoupangStockCode = getCoupangStockCode()
        coupangStock.buy(CoupangStockCode)
    }
    
    private fun getCoupangStockCode(): String{
        return "CPNG"
    }
}

 

위와 같이 작성한 어댑터 클래스를 아래와 같이 활용하면 됩니다.

fun main() {
    // 이태경이 작성한 coupangStock 클래스를 인스턴스화
    val coupangStock = coupangStock()
    
    // 회사 A 담당자가 작성한, 어댑터 클래스 인스턴스화
    val stockAdapter = stockAdapter(coupangStock)
    
    // 어댑터를 사용하여 이태경이 작성한 클래스 또한 정상적으로 buy 메소드를 사용가능하도록 설계
    stockAdapter.buy("Coupang")
    
    // 출력 : buy Coupang Stock
}

 

출처

 

Adapter pattern - Wikipedia

From Wikipedia, the free encyclopedia Design pattern in computer programming In software engineering, the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interfac

en.wikipedia.org

 

Adapter Design Pattern in Kotlin

What is it

medium.com

 

Design patterns: Adapter – With Kotlin examples – Narbase Technologies

Design patterns split into three main categories Creational, Structural and Behavioral, we explored the creational patterns and now we will move on to the second category the Structural patterns. These patterns focus on how to assemble objects and classes

narbase.com