Head First Design Pattern: 6 of 10
Oluwasanmi Aderibigbe
Posted on July 19, 2021
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())
}
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.
Posted on July 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024