The Adapter

Intent: Convert the interface of a class into another interface clients expect. The adapter lets classes work together that couldn't otherwise because of incompatible interfaces (Gamma et al., 1994).

Example: Many of the patterns require a consistent interface while implementation is allowed to vary. The strategy (see p. 50 of this book) 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.

images

Figure 2: Adapter example diagram.

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, its 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 (see p. 38) 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 (see p. 46) or decorator (see p. 28).

The delta between the interfaces should be small. If it is not, it may be that a facade (see p. 30) is more appropriate.

The adapter is typically implemented as a kind of “wrapper” that delegates to the foreign component (as shown). However, it can be implemented using inheritance when greater performance is needed. This requires multiple inheritances or a language that supports other abstract types, like interfaces and delegates.

For more information: https://tinyurl.com/y6nkmdf6

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.151.164