Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adapter Design Pattern - Kotlin
class AdapterDesignPattern {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(CSVAdapterImpl(CSVFormatterImpl()).formatText("Hello. Romman Sabbir. How are you?."))
}
}
}
/**
* Old interface from 3rd party vendor.
*/
interface TextFormatter {
fun formatText(input: String): String
}
/**
* Impl of old interface from 3rd party vendor.
*/
class TextFormatterImpl : TextFormatter {
override fun formatText(input: String): String =
input.replace(".", "\n")
}
/**
* Our new interface that should work with old interface.
*/
interface CSVFormatter {
fun formatText(input: String): String
}
/**
* Impl of our new interface that should work with old interface.
*/
class CSVFormatterImpl : CSVFormatter {
override fun formatText(input: String): String =
input.replace(".", ",")
}
/**
* Adapter that enable working new business logic with old interface [TextFormatter].
* [CSVAdapterImpl] take an instance of [CSVFormatter] as a parameter in constructor.
* We will execute our new logic by following the old interface.
*
* @param csvFormatter [CSVFormatter] instance.
*/
class CSVAdapterImpl constructor(private val csvFormatter: CSVFormatter) : TextFormatter {
/**
* We are calling [CSVFormatter] do our work according to our requirement instead of
* following the old implementation from the external vendor.
*
* @param input text that need to be formatted.
*
* @return formatted output as [String]
*/
override fun formatText(input: String): String = csvFormatter.formatText(input)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment