Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.

Adapter Design Pattern

One of the great real life example of Adapter design pattern is mobile charger. Mobile battery needs 3 volts to charge but the normal socket produces either 120V (US) or 240V (India). So the mobile charger works as an adapter between mobile charging socket and the wall socket.

We will try to implement multi-adapter using adapter design pattern in this tutorial.

So first of all we will have two classes – Volt (to measure volts) and Socket (producing constant volts of 120V).

Now we want to build an adapter that can produce 3 volts, 12 volts and default 120 volts. So first of all we will create an adapter interface with these methods.

Two Way Adapter Pattern

While implementing Adapter pattern, there are two approaches – class adapter and object adapter – however both these approaches produce same result.

  1. Class Adapter – This form uses java inheritance and extends the source interface, in our case Socket class.
  2. Object Adapter – This form uses Java Composition and adapter contains the source object.

Adapter Design Pattern – Class Adapter

Here is the class adapter approach implementation of our adapter.

Adapter Design Pattern – Object Adapter Implementation

Here is the Object adapter implementation of our adapter.

Notice that both the adapter implementations are almost same and they implement the SocketAdapter interface. The adapter interface can also be an abstract class.

Here is a test program to consume our adapter design pattern implementation.

When we run above test program, we get following output.

Adapter Design Pattern Class Diagram

adapter-pattern-java-class-diagram-4

Adapter Design Pattern Example in JDK

Some of the adapter design pattern example I could easily find in JDK classes are;

  • java.util.Arrays#asList()
  • java.io.InputStreamReader(InputStream) (returns a Reader)
  • java.io.OutputStreamWriter(OutputStream) (returns a Writer)

That’s all for adapter design pattern in java.

By admin

Leave a Reply

%d bloggers like this: