Pattern: Adapter


Context

Sometimes the protocol of an existing class will not match the protocol you require as a client of that class. It may be too detailed, or use terminology which is inappropriate for the client. We need an interface to adapt the protocol of a class into a protocol which clients expect.

Solution

Define an Adapter class containing an instance of the target class (Object Composition). The implementation of the adapter protocol converts client requests into the protocol that the target class expects. The number of methods in the adapter will be defined by the width of the client protocol. The amount of coding required to implement an adapter will depend on how similar the client and target protocols are.

As well as acting as an interpreter between client and adaptee, an adapter can supply additional functionality which is missing from the adaptee.

Example

Consider implementing a suite of graph classes. You might implement LineGraph and BarChart classes, and buy a PieChartControl class implemented by a 3rd party. There is some common behaviour between the various types of graphs, so LineGraph and BarChart would both be subclassed from a common Abstract Class Graph. PieChartControl would not conform to the Graph protocol.

Define an adapter class PieChart which is a subclass of Graph and contains an instance of PieChartControl. This adapter will implement the PieChart protocol in terms of the PieChartControl protocol.

Consequences

An adapter can interpret the protocol of the adaptee and its subclasses.

Known Uses

Value Model provides a value/value: interface for getting and setting a single value of other objects (in particular see the ValueAspectAdapter class).

Related Patterns