Card 02/ 08

ConceptDifficulty: Intermediate1 min

Adapter Pattern Structure: The Class Diagram

Target, Adapter and Adaptee, and the object adapter that holds the adaptee rather than inheriting it.

Adapter has four participants: the client, the target interface the client uses, the adaptee with the interface that does not fit, and the adapter that joins them. This card reads each role off the Gang of Four's diagram for the object adapter, then compares it with the class adapter, the other form the book gives.

The object adapter
Each participant and its role
ParticipantRole
TargetThe interface the client is written against, here with request().
ClientCalls request() on a Target, and knows nothing about the adaptee.
AdapteeThe existing class with a useful method under the wrong interface, specific_request().
AdapterImplements Target and holds an Adaptee; its request() calls specific_request() and translates.

The diagram shows the object adapter: the adapter holds a reference to an adaptee, the association arrow, and passes calls to it. The class adapter instead inherits from the adaptee and implements the target, so it is the adaptee with an extra interface. In Java that is class Adapter extends Adaptee implements Target, and in Python multiple inheritance does the same.

The object adapter is the form used almost everywhere. It adapts any subclass of the adaptee, because it holds whatever object it is given, and it exposes only the target's methods, so the client cannot reach past the translation. The class adapter saves one reference and can override the adaptee's methods, but it ties the adapter to one concrete class and shows the adaptee's whole interface alongside the target's.