Pages

Wednesday, 19 September 2012

Design Pattern - Adapter Pattern

What is it?

The adapter pattern can be described as follows. When you have to implement an interface, but you want to use another class’ (or interface’s) methods in order to implement it you are using the Adapter Pattern. An example will illustrate this much better than this definition.

Example Problem

Lets say I have an AddressBook, and I wish to display this AddressBook to a JTable. One solution (without using the Adapter Pattern) is to have my AddressBook implement the TableModel. This is not such a good idea, because I don’t want my AddressBook class (or object model) to be tied to Swing.

Solution (design)

I can provide a nice solution to this problem by using the Adapter Pattern. Instead of implementing the TableModel directly on the AddressBook, I instead create an intermediary adapter class. This adapter class actually uses the AddressBook methods in order implement the TableModel. So I would call this class the AddressBookTableAdapter. Review the code snippets below to get an idea of how this is implemented.
There is no need for an Adapter to subclass the AddressBook class. In fact, you should use the Delegation Pattern, instead of using subclass. The example below uses the Delegation Pattern instead of subclassing.

Code

 1: //AddressBook
 2: public class AddressBook{
 3:     List personList;
 4:
 5:     public int getSize(){…}
 6:     public int addPerson(…){…}
 7:     public Person getPerson(…){…}
 8:
 9: }
 1: //AddressBookTableAdapter
 2: public class AddressBookTableAdapter
 3: implements TableModel
 4: {
 5:      AddressBook ab;
 6:      public AddressBookTableAdapter( AddressBook ab ){
 7:         this.ab = ab;
 8:      }
 9:
 10:      //TableModel impl
 11:      public getRowCount(){
 12:          ab.getSize();
 13:      }
 14:
 15: }
 1: //Test
 2: public class Test{
 3:      public static void main( String[] args ){
 4:          AddressBook ab = //get reference to AddressBook somehow
 5:          AddressBookTableAdaptermodel =
 6:              new AddressBookTableAdapter( ab );
 7:          JTable table = new JTable( model );
 8:      }
 9: }

Why?

Now that you have seen the Adapter pattern, you ask why use it? Well, the answer to this question has already been provided in the example problem definition. You don’t want your object models implementing JavaVM specific interfaces becuase they might change in the future. Also, by implementing Swing interfaces directly into your object models, you make your code messy by introducing Swing event handling code there.
It’s a better idea to use the Adapter pattern. It will make it so that you can get the most out of your object model by limiting direct dependencies on interfaces (and perhaps classes) that you can’t control.

No comments:

Post a Comment