The Adapter

Listen to this post
Subscribe

Intent

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)

Example

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.

Diagram

Facade Pattern

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.

Testing

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.

More information

Visit the Net Objectives Pattern Repository: Adapter Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.