Adapter Design Pattern in Kotlin

1. Definition

The Adapter Design Pattern allows incompatible interfaces to work together. It acts as a bridge between two unrelated interfaces by providing what one interface expects from the other.

In this tutorial, we will learn how to implement an Adapter Design Pattern using Kotlin programming language.

2. Problem Statement

Imagine you're traveling abroad and you have an electrical device with a plug that's incompatible with the sockets in your hotel. The device has a two-pin plug, while the socket accepts three-pin plugs. Directly plugging the device won't work due to the difference in design.

3. Solution

Use an adapter – a device that can accept a two-pin plug on one end and has a three-pin plug on the other. This way, you can connect your device to the socket through the adapter without changing the device or the socket.

4. Real-World Use Cases

1. Travel adapters for electronic devices.

2. Memory card readers that allow different card types to be read by the same device.

3. Software libraries that bridge modern systems with legacy code.

5. Implementation Steps

1. Identify the existing interface that needs adapting (Target).

2. Recognize the interface that the client expects (Adaptee).

3. Create an adapter class that implements the target interface and has a reference to the adaptee.

4. Implement the methods of the target interface in the adapter by delegating to the adaptee.

6. Implementation in Kotlin Programming

// Target interface
interface ThreePinSocket {
    fun acceptThreePinPlug()
}
// Adaptee
class TwoPinPlug {
    fun insertTwoPinPlug() {
        println("Two-pin plug inserted!")
    }
}
// Adapter
class PlugAdapter(private val plug: TwoPinPlug) : ThreePinSocket {
    override fun acceptThreePinPlug() {
        plug.insertTwoPinPlug()
        println("Adapter made it compatible with three-pin socket!")
    }
}
fun main() {
    val twoPinPlug = TwoPinPlug()
    val adapter = PlugAdapter(twoPinPlug)
    adapter.acceptThreePinPlug()
}

Output:

Two-pin plug inserted!
Adapter made it compatible with three-pin socket!

Explanation:

1. ThreePinSocket is the target interface that our client (in this case, the socket in the hotel) expects.

2. TwoPinPlug is the adaptee – the existing functionality we want to adapt.

3. PlugAdapter is the adapter class. It takes a TwoPinPlug as a reference and implements the ThreePinSocket interface. It makes the two-pin plug compatible with the three-pin socket.

4. In the main function, we create a TwoPinPlug object and an adapter. We then use the adapter to connect the plug to the socket.

7. When to use?

The Adapter pattern is useful when:

1. You need to integrate classes with incompatible interfaces.

2. You want to use a class that doesn't meet the requirements of an interface directly.

3. You want to reuse existing classes in a new environment without modifying their code.

Comments