liveBook · Manning

Adapter

As explained in Object-Oriented Software Design in C++

The Adapter Design Pattern is a structural design pattern that converts one interface into another interface expected by clients so otherwise incompatible components can work together.

The Adapter Design Pattern integrates components whose interfaces do not match, especially when external or legacy code cannot be changed. It converts an adaptee’s interface into the target interface expected by clients. section 10.0 section 10.1

From duplicated conversions to adapters

An attendance report needs venue and fan data through AttendanceData, but FootballInfo returns a pair and VolleyballStats returns a struct. A flawed report performs both conversions itself, coupling reporting to every external representation. FootballData and VolleyballData instead implement AttendanceData, wrap their respective objects, and provide get_venue() and get_attendance(). AttendanceReport then accepts one AttendanceData object and no longer performs conversions. section 10.1.3

Choose the adapter form according to the integration needs:

  • Use an object adapter when composition is suitable, when an adapter may be shared, or when adaptee subclasses should also be wrapped. section 10.1.5
  • Use a class adapter when multiple inheritance is acceptable, the client should hide the adaptee type, or adaptee functions may need overriding. section 10.1.5
  • Keep conversion responsibilities inside adapters so clients depend on the target interface rather than external data representations. section 10.1.3
Figure 10.3 The generic model of the Adapter Design Pattern. Compare with figure 10.2. The Adapter class implements the Target interface. It adapts an Adaptee class by wrapping it so that the latter can work with the Target interface.

The generic model maps the Target interface to the Adapter, the Adapter to the wrapped Adaptee, and client requests to converted specific requests. section 10.1.4

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains interface conversion through wrapping, client simplification, generic roles, and multiple-inheritance alternatives.
Examples
Uses shape and text interfaces, plus FootballInfo and VolleyballStats adapted for an AttendanceReport.
What you can do after
Build it from scratch by implementing a target interface, wrapping an incompatible object, and translating its operations for clients.
How it connects
Connects interface conversion with object composition, inheritance, multiple inheritance, encapsulation, and client decoupling.

Also explained in

Compare how 9 books explain adapter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.