DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on • Edited on

1 1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top 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!!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more