DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on • Updated on

Head First Design Pattern: 6 of 10

I just learnt a new design from the Head First Design Pattern book. Today, I learnt about the Adapter.

According to Head First Design Patterns, the Adapter pattern is a pattern that allows you to convert the interface of a class into another interface clients expects.
The adapter lets classes work together that couldn't otherwise because of incompatible interfaces. It does so by wrapping existing classes and mapping requests from the existing class to the new system.

Implementing the Adapter pattern is pretty straight. For example you were asked to work on a feature for your mobile app that requires you to integrate a third party library that only accepts data in XML.

interface XMLProvider {
    fun sendData(): List<XML>
}

class XML(val data: String)

class JSON(val data: String)

class JSONNetworkingClass() {
    fun sendData(): List<JSON> = listOf(JSON("jsonnnnnn derulo"))
}

class XMLToJsonAdapter(val jsonNetworkingClass: JSONNetworkingClass) : XMLProvider {

    override fun sendData(): List<XML> {
        //convert json to xml.
        return jsonNetworkingClass.sendData().map { XML(it.data) }
    }
}

fun main() {
val xmLLibrary = XMLLibrary.init(XMLToJsonAdapter())
}
Enter fullscreen mode Exit fullscreen mode

When you need to use an existing class perhaps from legacy code or libraries and its interface is not one you need, use an adapter.
A common example of the adapter pattern would be the RecyclerView's adapter and Retrofit's adapters.

Latest comments (2)

Collapse
 
zbretz profile image
Zach

You're a beast. So consistent. Keep up the good work.

Collapse
 
sanmiade profile image
Oluwasanmi Aderibigbe

Thank you so much Zach! I really appreciate it!!