Adapter Pattern

Convert the interface of a class into another interface that clients expect. The Adapter pattern lets classes work together that could not otherwise because of incompatible interfaces.

Have a look at this cable as shown in image here. It is HDMI to VGA adapter. This cable with 2 end points acts as an adapter between 2 devices. HDMI-compatible devices including DVD players, TV boxes, Blu-ray players, game consoles and etc to TVs, monitors, projectors and more with VGA interface.

This example is analogous to adapter pattern.

Let's take 2 actors here one being Blu-ray player offering HDMI out and another actor is some old projector accepting only VGA input.

Projector is our client and blu-ray player is adaptee,

If you looks at it, feature remains same that is blu-ray output is video and projector too accepts video as input but only exposed input/output interfaces are not compatible.

Hence, we have this adapter cable which makes it possible for 2 devices to connect and function together.

So by definition, an adapter allows two incompatible interfaces to work together. In other words, the adapter pattern convert the interface of a class into another interface clients expects. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

From the above image, the Target interface defines the domain specific interface that the Client used, so the client collaborates with objects that implement the Target interface. On the other side of things, the Adaptee is the existing interface that needs adapting in order for our client to interact with it. The Adapter adapts the Adaptee to the Target interface - in other words, it translates the request from the client to the adaptee. This is object adapter pattern.

While class adapter pattern makes use of inheritance for the adapter. - A subclass of the target class needs to be adapted to fit the expected interface of the clients.

Below code snippet should make this concept clear.

The object adapter pattern that uses composition to reference an instance of the wrapped class within the adapter.

The class adapter pattern that implements the adapter using inheritance.

The adapter design pattern solves problems like:

  • How can a class be reused that does not have an interface that a client requires?

  • How can classes that have incompatible interfaces work together?

  • How can an alternative interface be provided for a class?