177
Chapter 5
CHAPTER 5
Adapter Pattern 5
Adapt or perish, now as ever, is nature’s inexorable
imperative.
—H. G. Wells
The presentations and conceptions of the average man
of the world are formed and dominated, not by the full
and pure desire for knowledge as an end in itself, but
by the struggle to adapt himself favorably to the
conditions of life.
—Ernst Mach
What Is the Adapter Pattern?
The basic motivation for the adapter pattern is to enable wider use of existing
classes. For example, let’s assume that there’s a class that does a particular job, and
does it well. We want to use this class in an application, but it just doesn’t fit all the
current requirements. We may want to expand its features, or combine it with some
other classes to provide additional functionality. The bottom line is that we must
adaptthis existing class to fit new requirements. This is what the adapter pattern
does; it allows a client to use an existing class by converting itsinterfaceinto one that
fits a new context. The key point to remember is that the existing class isn’t modi-
fied, but anadapter classthat has the right interface uses it or extends it to provide
the necessary functionality.
A Design Pattern for Potty Training
A good example of an adapter is thetoilet seat adapterused by toddlers that fits on
top of a traditional toilet seat. Let’s take a look at the context. We have alegacy
objectthat is the toilet seat, whose basic design hasn’t changed in years. It functions
well for its original adult users (probably why the design hasn’t changed). Let’s look
at the new context in Figure 5-1. We now need to adapt it for use by a toddler. The
problem is obvious—incompatible interfaces! The legacy toilet seat was designed to