23.07.2012 Views

Design Patterns Explained

Design Patterns Explained

Design Patterns Explained

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Field Notes: The Adapter Pattern<br />

Chapter 7 • The Adapter Pattern 1O3<br />

Often, I will be in a situation similar to the one above, but the object<br />

being adapted does not do all the things I need.<br />

In this case, I can still use the Adapter pattern, but it is not such a<br />

perfect fit. In this case,<br />

• Those functions that are implemented in the existing class can<br />

be adapted.<br />

• Those functions that are not present can be implemented in the<br />

wrapping object.<br />

This does not give me quite the same benefit, but at least I do not<br />

have to implement all of the required functionality.<br />

The Adapter pattern frees me from worrying about the interfaces of<br />

existing classes when I am doing a design. If I have a class that does<br />

what I need, at least conceptually, then I know that I can always use<br />

the Adapter pattern to give it the correct interface.<br />

This will become more important as you learn a few more patterns.<br />

Many patterns require certain classes to derive from the same class.<br />

If there are preexisting classes, the Adapter pattern can be used to<br />

adapt it to the appropriate abstract class (as Circle adapted<br />

XXCircle to Shape).<br />

There are actually two types of Adapter patterns:<br />

• Object Adapter pattern— The Adapter pattern I have been using is<br />

called an Object Adapter because it relies on one object (the<br />

adapting object) containing another (the adapted object).<br />

• Class Adapter pattern— Another way to implement the Adapter<br />

pattern is with multiple inheritance. In this case, it is called a<br />

Class Adapter pattern.<br />

You can do more<br />

than wrapping<br />

Adapter frees you<br />

from worrying about<br />

existing interfaces<br />

Variations: Object<br />

Adapter, Class<br />

Adapter

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!