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)
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: }
No comments:
Post a Comment