Java Reference
In-Depth Information
Adapter
Also known as Wrapper
Pattern Properties
Type: Structural, Object
Level: Component
Purpose
To act as an intermediary between two classes, converting the interface of one class so that it can be used with the
other.
Introduction
One of the frequently cited advantages of object-oriented programming is that it enables code reuse. Since data
and behavior are centralized in a class, you can (at least in principle) move the class from one project to another
and reuse the functionality with very little effort.
Unfortunately, we developers are somewhat limited in our ability to predict the future. Since we cannot know in
advance what the coding requirements will be for a project in the future, we cannot always know how to design a
class for optimum reusability.
Imagine that, in order to speed up the development of your Personal Information Manager application, you decide
to cooperate with one of your foreign friends. He has been working on a similar project and he can provide you
with a commercial implementation of an address system. But when you receive the files, the interface doesn't
match the interfaces you have been using. To make matters worse, the code is not in English, but in your friend's
native language.
You see yourself faced with two equally unattractive solutions.
Your first option is to rewrite the new component so that it implements all the required interfaces. Rewriting the
new component is a bad idea because you will have to do the same rewrite every time you receive the newest
version from your friend.
The second option is to rewrite your own application and start using the new (foreign) interfaces. Here the
downside is that you have to go through your whole code to change every occurrence of the old interfaces, and
your code becomes harder to understand because you don't speak your friend's native language. What might be
meaningful names to your friend don't mean anything to you.
What you need here is a translator—a component that translates the calls to one interface into calls on another
interface. This is what the Adapter pattern does. It behaves similarly to a power adapter, converting one type into
another otherwise-incompatible type. By using the Adapter pattern your application can keep on using your
interfaces while allowing use of the new components. And when a new version arrives, the only thing you have to
change is the Adapter.
Applicability
Use Adapter when:
You want to use an object in an environment that expects an interface that is different from the object's interface.
Interface translation among multiple sources must occur.
An object should act as an intermediary for one of a group of classes, and it is not possible to know which class
will be used until runtime.
 
Search WWH ::




Custom Search