Java Structural Design Patterns – Adapter Pattern

Adapter pattern comes under Structural Design Pattern. This pattern combines the capability of two independent interfaces and works as a bridge between two incompatible interfaces.

The Adapter pattern usually involves one single class which provides functionality to reuse the incompatible interface. The bridge class is adapted as per client requirement and provides the functions of the incompatible interface. You take this approach if:

  • You need to reuse the class that does not have an interface as per client requirement
  • Your intent is to provide an alternative interface for a class

<Here are ALL other Java Design Patterns, explained in detail with examples>

Adapter Method Pattern by Example

This pattern can be understood with a simple real-life example of charger and socket adapter. When you travel across the country, you will find the electrical plugs are different and you can not directly use the plug points for your devices.

So what do you do in such scenario? you use an Adapter which has the sockets that are compatible with your device and it also has country-specific extensions which you can choose based on your country of travel. Well, this is what exactly achieved in Adapter Pattern.

Let us try to convert the above example into code. At first, define a simple adapter interface with the connect method.

Now we will have a couple of concrete implementation of the above adapter

for the UK

for Germany

Below is our device charger class

Observer that we have an instance of Adapter into our charger. This adapter will be used to connect to the country-specific socket.

Running the Example

Output:

Advantages:

  • The main advantage of this pattern is that it helps achieve reusability and flexibility.
  • A client can use a different interface and can use polymorphism to use different implementations of adapters.

Conclusion

In this article, we understood the Adapter Pattern with the help of a simple example. The source code is available in our Github repository.

Download Code

 

 

Similar to Flyweight Pattern, if you wish to have a look at other Java Design Patterns, then check this out. You can also find more sample in another language at Wiki Page

Add a Comment

Your email address will not be published. Required fields are marked *