Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created January 23, 2022 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/372c80e0edb620408bc273d93b0606f3 to your computer and use it in GitHub Desktop.
Save rommansabbir/372c80e0edb620408bc273d93b0606f3 to your computer and use it in GitHub Desktop.
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