Adaptor Pattern
(from Design
Patterns)
Synopsis
Convert the interface of a class into another interface clients
expect. Adapter lets classes work together that couldn't otherwise because
of incompatible interfaces.
Context
You want to use an existing class whose interface does not match the one
you need.
Forces
-
The interface difference should be transparent to clients.
-
The original class should not have to anticipate the interface change.
-
The implementation of the original class should still be able to evolve.
Solution
Compose the existing object (the subject) within an Adaptor object that
implements the desired interface. The Adaptor forwards to the subject
while possibly performing additional actions.
Consequences
-
Subjects do not have to anticipate Adaptors. In fact, Adaptors are usually
used when integrating a foreign object. Since it is treated as a black box
by the Adaptor, the subject can still evolve.
-
The Adaptor can provide additional functionality that the subject didn't
have in its interface. In this way, an Adaptor is like a Decorator.
-
An Adaptor can provide several extra interfaces, not just one.
This could include the original object's interface.
Implementation
-
You can use multiple inheritance instead of object composition to make an
Adaptor. The Adaptor inherits from the subject class and the interface it
needs to conform to. However, this commits to a particular concrete
subject class and inhibits co-evolution.
-
It is tempting to put lots of additional capabilities in the Adaptor
object. An Adaptor should ideally just convert between one interface and
another. Adding capabilities should be done with Decorators.
See Design
Patterns for sample code.
Known Uses
-
The server stub which receives an RPC and forwards it to the server
function is an Adaptor.
-
InterViews uses an Adaptor to let graphical objects like lines and
polygons be used as user interface elements.
-
Distributed object databases like CORBA use Adaptors to integrate native
language objects into the database. Adaptors are also used to make
non-objects, like text files, look like objects.
Thomas Minka
Last modified: Fri Jan 17 18:37:18 EST 1997