When do we need to go for Adapter pattern? If possible give me a real world example that suits that pattern.
When do we need to go for Adapter pattern? If possible give me a real world example that suits that pattern.
EuroPlug connector connects only to european electrical sockets:
interface EuroPlug {
fun plugIn()
}
class EuroSocket {
fun supplyCurrent(plug: EuroPlug) = plug.plugIn()
}
USPlug connector connects only to US electrical sockets:
interface USPlug {
fun plugIn()
}
class USSocket {
fun supplyCurrent(plug: USPlug) = plug.plugIn()
}
When we have USSocket and EuroPlug, we create an adapter to convert the EuroPlug to USPlug:
class EuroToUSPlugAdapter(private val euroPlug: EuroPlug) : USPlug {
override fun plugIn() = euroPlug.plugIn()
}
Now EuroToUSPlugAdapter adapts the interface USPlug of the already existing class USSocket without changing it.
Here we have a USSocket but with a EuroPlug object. So, we pass the EuroPlug object to the EuroToUSPlugAdapter which does the work of converting a EuroPlug to the USPlug:
fun main() {
val usSocket = USSocket()
val euroPlug = object : EuroPlug {
override fun plugIn() {
println("Euro plug adapted for US Socket")
}
}
val euroAdapter = EuroToUSPlugAdapter(euroPlug)
usSocket.supplyCurrent(euroAdapter)
}
That's it! This is how the adapter pattern allows two incompatible interfaces to work together. Hope that helps.
I found the clearest and kind of real life example in Bharath Thippireddy design pattern course.
We have WeatherUI class which is looking for temperature by zip-code and we have WeatherFinderImpl class which knows temperature by city name so we need to create WeatherAdapter class which will take zipcode, change it to city name and call WeatherFinder class to return proper temperature.
WeatherUi class:
public class WeatherUI {
public void showTemperature(int zipcode) {
//I just have zipcode
}
}
and WeatherFinder interface:
public interface WeatherFinder {
int find(String city);
}
and WeatherFinderImpl which can find temperature only by city name:
public class WeatherFinderImpl implements WeatherFinder{
@Override
public int find(String city) {
return 25;
}
}
having these three in WeatherUI class we can create a method which will translate zipcode into city or we can create a new adapter class:
public class WeatherAdapter {
public int findTemperature(int zipcode){
String city = null;
//here most probably we would take it from db, in example hardcode is enough
if(zipcode == 63400){
city = "Ostrow Wielkopolski";
}
WeatherFinder finder = new WeatherFinderImpl();
int temperature = finder.find(city);
return temperature;
}
}
and call it in WeatherUI:
public class WeatherUI {
public void showTemperature(int zipcode) {
WeatherAdapter adapter = new WeatherAdapter();
System.out.println(adapter.findTemperature(63400));
}
}
test for it is as simple as:
public static void main(String[] args) {
WeatherUI ui = new WeatherUI();
ui.showTemperature(63400);
}
From: Alexey Soshin's Book “Kotlin Design Patterns and Best Practices Second Edition”:
The main goal of the Adapter design pattern is to convert one interface to another interface. In the physical world, the best example of this idea would be an electrical plug adapter or a USB adapter. Imagine yourself in a hotel room late in the evening, with 7% battery left on your phone. Your phone charger was left in the office at the other end of the city. You only have an EU plug charger with a Mini USB cable. But your phone uses USB-C, as you had to upgrade. You're in New York, so all of your outlets are (of course) USB-A. So, what do you do? Oh, it's easy. You look for a Mini USB to USB-C adapter in the middle of the night and hope that you have remembered to bring your EU to US plug adapter as well. Only 5% battery left – time is running out! So, now that we understand what adapters are for in the physical world, let's see how we can apply the same principle in code. Let's start with interfaces. USPlug assumes that power is Int. It has 1 as its value if it has power and any other value if it doesn't:
interface USPlug {
val hasPower: Int
}
EUPlug treats power as String, which is either TRUE or FALSE:
interface EUPlug {
val hasPower: String // "TRUE" or "FALSE"
}
For UsbMini, power is an enum:
interface UsbMini {
val hasPower: Power
}
enum class Power {
TRUE, FALSE
}
Finally, for UsbTypeC, power is a Boolean value:
interface UsbTypeC {
val hasPower: Boolean
}
Our goal is to bring the power value from a US power outlet to our cellphone, which will be represented by this function:
fun cellPhone(chargeCable: UsbTypeC) {
if (chargeCable.hasPower) {
println("I've Got The Power!")
} else {
println("No power")
}
}
Let's start by declaring what a US power outlet will look like in our code. It will be a function that returns a USPlug:
// Power outlet exposes USPlug interface
fun usPowerOutlet(): USPlug {
return object : USPlug {
override val hasPower = 1
}
}
Our charger will be a function that takes EUPlug as an input and outputs UsbMini:
// Charger accepts EUPlug interface and exposes UsbMini
// interface
fun charger(plug: EUPlug): UsbMini {
return object : UsbMini {
override val hasPower=Power.valueOf(plug.hasPower)
}
}
Next, let's try to combine our cellPhone, charger, and usPowerOutlet functions:
cellPhone(
// Type mismatch: inferred type is UsbMini but // UsbTypeC
was expected
charger(
// Type mismatch: inferred type is USPlug but //
EUPlug was expected
usPowerOutlet()
)
)
As you can see, we get two different type errors – the Adapter design pattern should help us solve these. Adapting existing code We need two types of adapters: one for our power plugs and another one for our USB ports. We could adapt the US plug to work with the EU plug by defining the following extension function:
fun USPlug.toEUPlug(): EUPlug {
val hasPower = if (this.hasPower == 1) "TRUE" else
"FALSE"
return object : EUPlug {
// Transfer power
override val hasPower = hasPower
}
}
We can create a USB adapter between the Mini USB and USB-C instances in a similar way:
fun UsbMini.toUsbTypeC(): UsbTypeC {
val hasPower = this.hasPower == Power.TRUE
return object : UsbTypeC {
override val hasPower = hasPower
}
}
Finally, we can get back online again by combining all those adapters together:
cellPhone(
charger(
usPowerOutlet().toEUPlug()
).toUsbTypeC()
)
The Adapter design pattern is more straightforward than the other design patterns, and you'll see it used widely. Now, let's discuss some of its real world uses in more detail.
Adapters in the real world
You've probably encountered many uses of the Adapter design pattern already. These are normally used to adapt between concepts and implementations. For example, let's take the concept of a JVM collection versus the concept of a JVM stream. A list is a collection of elements that can be created using the listOf() function:
val list = listOf("a", "b", "c")
A stream is a lazy collection of elements. You cannot simply pass a collection to a function that receives a stream, even though it may make sense:
fun printStream(stream: Stream<String>) {
stream.forEach(e -> println(e))
}
printStream(list) // Doesn't compile
Luckily, collections provide us with the .stream() adapter method:
printStream(list.stream()) // Adapted successfully
Many other Kotlin objects have adapter methods that usually start with to as a prefix. For example, toTypedArray() converts a list to an array.
Caveats of using adapters
Have you ever plugged a 110 V US appliance into a 220 V EU socket through an adapter, and fried it totally? If you're not careful, that's something that could also happen to your code. The following example uses another adapter, and it also compiles well:
val stream = Stream.generate { 42 }
stream.toList()
But it never completes because Stream.generate() produces an infinite list of integers. So, be careful and adopt this design pattern wisely.