Applied Design Patterns with Java
Structural :: Adapter (137) {C ch 9}
Collaborations
- Clients call operations on an Adapter
instance. In turn, the Adapter calls Adaptee operations that carry out the request.
Consequences
Class and object adapters have different trade-offs. A class Adapter
- adapts Adaptee to Target by committing to a concrete Adapter class.
As a consequence, a class adapter won't work to adapt a class and all its subclasses.
- lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of Adaptee.
- introduces only one object, and no additional pointer indirection is
needed to get to the adaptee.
An object Adapter
- lets a single Adapter work with many Adaptees - the Adaptee itself and
all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once.
- makes it harder to override Adaptee behavior. It will require subclassing
Adaptee and making Adapter refer to the subclass rather than the Adaptee itself.
Here are other issues to consider when using the Adapter:
- How much adapting does Adapter do? Adapters vary in the amount of work they do to adapt Adaptee to the Target interface.
The amount of work Adapter does depends on how similar the Target interface is to Adaptee's.
- Pluggable adapters.
A class is more reusable when restricting the assumptions other classes must make to use it. By building interface
adaptation into a class, the assumption other classes see the same interface is eliminated. The term pluggable
Adapter
describes classes with built-in interface adaptation. Consider
a TreeDisplay widget that can display tree structures graphically. Different
tree structures will have different interfaces. In a directory hierarchy, children might be accessed with a GetSubdirectories
operation, whereas in an inheritance hierarchy, the corresponding operation might be called GetSubclasses. A reusable
TreeDisplay widget must be able to display both kinds of hierarchies even if they use different interfaces. In
other words, the TreeDisplay should have interface adaptation built into it.
- Using two-way adapters to provide transparency. A potential problem with adapters is that they aren't transparent to all clients.
An adapted object no longer conforms to the Adaptee interface, so it can't be used as is wherever an Adaptee object
can. Two-way adapters can provide such transparency. Specifically, they're useful when two different clients need
to view an object differently.
Catalog Structural Prev Next