Adapter

The Adapter pattern allows us to use a pre-existing interface without modifying the source. Let's imagine that we want to teach a cat how to bark. The following diagram shows how we can implement this:


The preceding diagram contains the Meowable and Barkable interfaces. The Cat class implements the Meowable interface and the Dog class implements the Barkable interface. To teach a cat how to bark, we should pass an instance of the Barkable type to an instance of the Cat class. For this, we can create the Adapter class, which has implemented both interfaces, and invoke the bark method from meow.

The Meowable and Barkable interfaces look like this:

interface Barkable {
fun bark() {
println("bark")
}
}

interface Meowable {
fun meow() {
println("meow")
}
}

The Cat and Dog classes takes instances of the Barkable and Meowable types as parameters:

class Cat(private val meowable: Meowable) {
fun voice() {
meowable.meow()
}
}

class Dog(private val barkable: Barkable) {
fun voice() {
barkable.bark()
}
}

The Adapter class may look like this:

class Adapter: Barkable, Meowable {
override fun meow() {
bark()
}
}

Let's run the program:

fun main(args: Array<String>) {
Cat(Adapter()).voice()
}

The following is the output:

bark
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119