Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. (GoF)
Many of the patterns require a consistent interface while implementation is allowed to vary. The Strategy is a good example. If such a pattern is used then client objects are designed to that interface, allowing for additional implementations to be added in the future without changes to the clients (following open-closed). If a new implementation is provided, perhaps a purchased component or an implementing class provided by another team, then it may not fit into the existing pattern. An Adapter can be added to solve this problem.
Qualities and principles
The Adapter class only changes the interface. Clients couple only to the original interface and never to the real interface of the foreign (supplied) object. Adapters contain no redundant implementation with existing components. The actual component, it’s real interface, and the fact that it is “foreign” is hidden from clients. Adapters preserve existing open-closed relationships and create substitutability with entities that are conceptually the same but cannot be practically treated the same. The Adapter separates the concern of the real interface from the needed behavior.
An Adapter can be tested using a Mock Object in place of the supplied/foreign component.
Questions and concerns
The Adapter requires that the adapted component be fully capable. If it lacks some of the functionality that the local components have, then behavior(s) will have to be added to it. This can be done with either a Proxy or Decorator.
The delta between the interfaces should be small. If it is not, it may be that a Façade is more appropriate.
The Adapter can be implemented using inheritance when consistent performance is important.
This is Scott Bain. Visit us at www.netobjectives.com.