Java Reference
In-Depth Information
Chapter 3. Adapter
As a software developer, you write classes whose methods are called by clients. You may be
able to control the interface that the client expects, but often you will not be able to do so. The
most common example of an expectation that you must frequently fulfill is the
implementation of the main() method that the Java interpreter expects. Services such as
Swing also often include features that require you to support a predefined interface.
When you need to implement an expected interface, you may find that an existing class
performs the services a client needs but with different method names. You can use the
existing class to meet the client's needs by applying the A DAPTER pattern. The intent of
A DAPTER is to provide the interface a client expects, using the services of a class with a
different interface.
Adapting in the Presence of Foresight
When you need to adapt your code to meet a client's needs, you may find that the client
planned for such circumstances. This is evident when the client's developers provide a Java
interface that defines the services the client code needs, as in the example shown in
Figure 3.1. A client class in a package makes calls to a service() method that is declared
in a Java interface. Suppose that you have found an existing class with a method that can
fulfill the client's needs, but the name of the method is usefulMethod() . You can adapt the
existing class to meet the client's needs by writing a class that extends ExistingClass ,
implements ThoughtfulInterface , and overrides service() so that it delegates its
requests to usefulMethod() .
Search WWH ::




Custom Search