Java Design Patterns – Adapter pattern

Adapter pattern was created to help with problems like adding new components to the old system or convert interface of the class to another interface that clients expect.

In this post, you can find:

  • example situation when to use Adapter design pattern
  • Adapter pattern code structure in Java
  • example how to use the Adapter pattern

If you want to connect new type of cable to the old device you will need to use an adapter. The similar situation could happen when you writing code. When you want to connect the new component to the old system. Another situation when you should think about using adapter pattern. The class that you have uses a specific type of data. You need to create an instance of this class. Unfortunately, you don’t have exactly the same type of data that the class needs but you can convert it. In the adapter class, you can convert data that you have and create the class instance using converted data.

Adapter pattern example in Java

In this post, I want to show you simple example. We have two type of phone: iPhone with the lightning connector and Android phone with MicroUSB connector. If you want to charge iPhone with MicroUSB cable you need to use the adapter. Let’s write it!

Interfaces

We would have two methods: first to connect cable and second to charge the phone.

Classes that implement these Interfaces

We have boolean that is true when the cable is connected. If connected is true recharge() method write message to the console that phone is recharging.

Adapter class

The class implementing FormatAndroidPhone interface. In the constructor, we saving an instance of iPhone and we implement AndroidPhone methods using functions from iPhone class. In method useMicroUsb() we write to console that MicroUSB adapter is connected.

How to use Adapter Pattern?

Look at Client class:

Console output:

Console result

We want to use Adapter class. First, we create the instance of iPhone class. Next, we need to create the instance of Adapter class as the parameter we give the instance of iPhone class. Now we can use methods on the instance of the adapter class.

You can find the code used in this article on my GitHub: Adapter Pattern

Adapter pattern is simple and easy to learn. Write some code and use this design pattern on your own example. That’s the easiest way to learn!

Good luck!

Want more? Look at my others post about Design Patterns

Be First to Comment

Leave a Reply

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