Vainolo's Blog

Adapter Design Pattern – Sequence Diagram

leave a comment

The Adapter (or Wrapper) design pattern is used when you want to adapt a class to an interface that it can implement.

One example where this pattern can be used is in the eclipse draw2d framwork. This framework is build on top of SWT, but this is just because of historical reasons. To work, draw2d only needs a Canvas on which it draws. In the current implementation, there is a class that takes the canvas and wraps it into a Canvas interface for use with draw2d. So theoretically (and practically, since this is being done in the new version of draw2d), we could take an AWT canvas and wrap it so that it can be used with draw2d. And we could do the same for a GWT canvas! cool, right? But anyway, If you didn’t get this, let’s try one more time using UML class and sequence diagrams:

The class diagram of the Adapter patterns is pretty simple. You have a client that know how to work with an existing class and you want to replace this class with a new implementation without having to change: 1) the functionality of the client (except maybe how he creates the class); and 2) Without changing the interface of your new implementation (because while I say here new, it doesn’t mean you wrote it. It simply means that it replaces the existing implementation). The result would look something like this:

adapter.class.diagram

yUML code:
[Client]->[Adapter|+interfaceMethod()]
[Adapter]+->[Implementation|+implementationMethod()]

As usual, the class diagram doesn’t tell us enough information to understand what is happening, so let’s look at the sequence diagram of this pattern:

adapter.sequence.diagram

WebSequenceDiagrams.com code:
Client->Adapter:interfaceMethod()
note right of Adapter:
translate parameters
end note
Adapter->Adapter:
Adapter->Implementation:implementationMethod()
Implementation-->Adapter:
note right of Adapter:
translate result
end note
Adapter->Adapter:
Adapter-->Client:

As you can see, the adapter simply translates the parameters back and forth so the client and the implementation can communicate. That is all. No magic here :-).

 

Enhanced by Zemanta

Written by vainolo

January 17th, 2013 at 9:51 pm

Leave a Reply

%d bloggers like this: