Professional Documents
Culture Documents
Adapter Pattern: or Building A Wrapper Class
Adapter Pattern: or Building A Wrapper Class
toString(3) //ERROR
toString(Integer(3)) //Ahhhhh wrapped!
Another Example:
EmailSender
Spose I am asked to write an email sender.
public EmailSender()
{
spam = new SpamSender(); //creates a SpamSender inside this class.
} //This is what we are wrapping around!
EmailSender
+sendEmail(:EmailAddress):void
SpamSender
+sendSpam(:EmailAddress, :EmailAddress):int
Another Example (cont.)
Collaboration diagram
:Driver
1: sendEmail(:EmailAddress) : void
:EmailSender
:SpamSender
Adapter Pattern UML
UML diagram:
Adapter Adaptee
Now can use Adapter in
place of Adaptee.
Adapter Pattern UML May Vary
As Ill say many times, design patterns may
be (slightly) altered to fit your needs.
Theyre just patterns.
Inheritance will extend existing code, but may not hide the old
code.
If EmailSender inherits from the SpamSender, then the
interface will include the inherited method sendSpam.
Aurgh! We wanted to get rid of that, or hide it.
We could override the sendSpam, but then we have an
interface with a misleading method name (sendSpam) that
doesnt sound anything like sendEmail.
Better option: Use composition to completely hide the old
code.
How Different From Faade?
Very similar dealing with an interface to pre-existing classes.