Till now, we have discussed all creational type of design patterns. In this and next series of posts, we will be creating a demo about structural design patterns. In this series, our first design pattern is Adapter design pattern. As said, this design pattern is structural design pattern. This design pattern combines the capabilities of two independent interfaces. It basically acts like a bridge between two incompatible interfaces.
Easiest example to understand adapter pattern in real life is the electric socket in different continents provide different voltages. A traveler from Asia can use an adapter in Europe to get 240 V of electricity for electronic devices.
When to use Adapter Design Pattern?
When a client expects different interface than available, at that time adapter pattern can help to convert a interface of a class into another interface that client can use. Adapter pattern allows reuse of lot of code and it is one of the major reasons why it is most favorable among software engineering. A real example you would find in JDK libraries of InputStreamReader and OutputStreamWriter.
How to use Adapter Design Pattern?
So in this implementation, we will show how to use Adapter design pattern. We have a traveler from Asia traveling in Europe, he wants to use his electronic device which needs 240 V of electricity from socket, but Europe only provides 120 V of electricity. We will design an adapter class that will convert 120 V of electricity to 240 V of electricity.
Our target class or client class is AsiaSocket, as shown below:
It’s a simple class with a method
Our adaptee class is EuropeSocket which implements an interface IEuropeSocket as shown below:
Now we will implement an Adapter class that will provide adapter between Europe and Asia Socket classes. This will look like below:
This class has a constructor to instantiate AsiaSocket and implements IEuropeSocket interface.
Now in our demo class, we will show how to use this adapter pattern.
If you run this demo class, the output will show that we will be getting electricity of 240 V for asian electronic devices in europe.
In this post, we showed how to use Adapter pattern. The demo code will be available on github repository here.