The Adapter Pattern: Putting A Square Peg in A Round Hole!
The Adapter Pattern: Putting A Square Peg in A Round Hole!
PuttingaSquarePeginaRound
Hole!
WrappingObjectstoUnifyInterfaces
Question:Whatpatternwrapsobjectstogivethemnew
functionality?
Nowwewrapobjectswithadifferentpurpose:
Tomaketheirinterfaceslooklikesomethingtheyarenot
Tosimplifytheinterfacesofobjects
Adapters
Realworldisfullofthem!
Someexamples?
Objectorientedadapters
Scenario:youhaveanexistingsoftwaresystemthatyouneedtoworka
newvendorlibraryinto,butthenewvendordesignedtheirinterfaces
differentlythanthelastvendor.
Your Existing
System
Vendor
Class
Whattodo?Writeaclassthatadaptsthenewvendorinterfaceintotheone
And talks to the vendor interface to service
youreexpecting.
The adapter
implements
the
interface
your classes
Your Existing
expect
System
your requests
Adapter
Vendor
Class
==
No code changes
New code
Vendor
Class
No code changes
Ifitwalkslikeaduck..
Ifitwalkslikeaduckandquackslikeaduck,thenit
mightbeaduckturkeywrappedwithaduckadapter.
public interface Duck {
public void quack ();
public void fly ();
}
public class MallardDuck implements Duck {
public void quack () {
System.out.println(Quack);
}
public void fly ( ) {
System.out.println (I am flying);
}
}
Meetthefowl!
Now.
LetssayyouareshortonDuckobjectsandwouldliketousesome
Turkeyobjectsintheirplace.
Cantusethemoutrightbecausetheyhaveadifferentinterface .
First, you need to implement the interface of
the type you are adapting to. This is the
interface your client expects.
TheAdapterPatternDefined
The Adapter Pattern converts the interface of a class into another
interface the clients expect. Adapter lets classes work together that
couldnt otherwise because of incompatible interfaces.
<<Interface>>
Target
request ( )
Client
The client sees only the
Target interface.
Adapter
request ( )
Adaptee
specificRequest ()
ObjectandClassAdapters
TherearetwotypesofAdapters
ObjectAdapter:whatwehaveseensofar.
ClassAdapter:notascommonasitusesmultipleinheritance,whichisnt
possibleinJava.
Adaptee
specificRequest ()
<<Interface>>
Target
request ( )
Client
Adapter
request ( )
Question: Object Adapters and Class Adapters use two different means of adapting the
adaptee (composition versus inheritance). How do these implementations affect the
flexibility of the adapter?
RealWorldAdapters
OldworldEnumerators
NewworldIterators
Andtodaylegacycodethatexposes
theEnumeratorinterface.Yetwewant
newcodetouseIterators.Needan
adapter.
<<interface>>
Enumeration
hasMoreElements ( )
nextElement ( )
<<interface>>
Iterator
hasNext ( )
next ( )
remove ( )
Enumeration has a
simple interface.
Tells whether there
are any more elements
in the collection.
Returns the next
element
Tells you if you have
looked at all the
elements
Gets the next one
Removes an item
from the
collection
AdaptinganEnumerationtoan
Iterator
Firststep:examinethetwointerfaces
Target interface
<<interface>>
Iterator
hasNext ( )
next ( )
remove ( )
<<interface>>
Enumeration
hasMoreElements ( )
nextElement ( )
Adaptee interface
DesigningtheAdapter
Your new code
gets to use
Iterators, even
if theres
really an
Enumeration
underneath.
EnumerationIterator
is the Adapter
<<interface>>
Iterator
hasNext ( )
next ( )
remove ( )
EnumerationIterator
hasNext ( )
next ( )
remove ( )
<<interface>>
Enumeration
hasMoreElements ()
nextElement ()
Dealingwiththeremove()method
Enumerationisareadonlyinterfaceitdoesnot
supporttheremove()method.
Impliesthereisnorealwaytoimplementafullyfunctioning
remove()method.
Thebestthatcanbedoneistothrowaruntimeexception.
Iteratordesignersforesawtheneedandhaveimplementedan
UnsupportedOperationException.
Heretheadapterisnotperfectbutisareasonable
solutionaslongastheclientiscarefulandtheadapteris
welldocumented.
EnumerationIteratorTheCode
public class EnumerationIterator implements Iterator {
Enumeration enum;
public EnumerationIterator (Enumeration enum) {
this.enum = enum;
}
public boolean hasNext () {
return enum.hasMoreElements ( );
}
public Object next ( ) {
return enum.nextElement ( );
}
public void remove ( ) {
throw new UnsupportedOperationException ( );
}
}
Question: Some AC adapters do more than just change the interface -- they add other
features like surge protection, indicator lights, and other bells and whistles.
If you were going to implement
these kinds of features, what pattern would you use?
Summary
Whenyouneedtouseanexistingclassanditsinterfaceisnotthe
oneyouneed,useanadapter.
Anadapterchangesaninterfaceintooneaclientexpects.
Implementinganadaptermayrequirelittleworkoragreatdealof
workdependingonthesizeandcomplexityofthetargetinterface.
Therearetwoformsofadapterpatterns:objectandclassadapters.
Classadaptersrequiremultipleinheritance.
Anadapterwrapsanobjecttochangeitsinterface,adecorator
wrapsanobjecttoaddnewbehaviorsandresponsibilities.