Adapter Pattern

Summary

  • The Adapter pattern joins together types that were not designed to work with each other.
  • The Adapter pattern enables a system to use classes whose interfaces don't quite match its requirements.

Different Types of Adapters

Class adapters

  • Simple and versatile, invisible to the client.
  • A class adapter implements an interface and inherits a class.
  • Overriding behaviour can be done more easily with a Class adapter.

Class diagram: (see Class Adapter Pattern code review)

Class Adapter Pattern class diagram of sample code download

Object adapters

  • Extensible to subclasses (inherited classes) of the adapter.
  • Adding behaviour can be done more easily with an Object adapter.

Two-way adapters

  • Enables different clients to view an object differently.
  • The Two-way adapter addresses the problem where the characteristics of one system have to be used in the other, and vice versa. An Adapter class is set up to absorb the important common methods of both and to provide adaptations to both.

Class diagram: (see Two-way Adapter Pattern code review)

Two-way Adapter Pattern class diagram of sample code download

Pluggable adapters

  • Presence of adapter is transparent; it can be put in and taken out.
  • The Pluggable adapter sorts out which object is being plugged in at the time. Once a service has been plugged in and its methods have been assigned to the delegate objects, the association lasts until another set of methods is assigned.

Class diagram: (see Pluggable Adapter Pattern code review)

Pluggable Adapter Pattern class diagram of sample code download

Usage

Use the Adapter pattern when you want to:

  • Create a reusable class to cooperate with yet-to-be-built classes.
  • Change the names of methods as called and as implemented.
  • Support different sets of methods for different purposes.