Java Reference
In-Depth Information
Bridge
This example shows how to use the Bridge pattern to extend the functionality of a to-do list for the PIM. The
to-do list is fairly straightforward—simply a list with the ability to add and remove Strings .
For the Bridge pattern, an element is defined in two parts: an abstraction and an implementation. The
implementation is the class that does all the real work—in this case, it stores and retrieves list entries. The general
behavior for the PIM list is defined in the ListImpl interface.
Example A.138 ListImpl.java
1. public interface ListImpl{
2. public void addItem(String item);
3. public void addItem(String item, int position);
4. public void removeItem(String item);
5. public int getNumberOfItems();
6. public String getItem(int index);
7. public boolean supportsOrdering();
8. }
The OrderedListImpl class implements ListImpl , and stores list entries in an internal ArrayList object.
Example A.139 OrderedListImpl.java
1. import java.util.ArrayList;
2. public class OrderedListImpl implements ListImpl{
3. private ArrayList items = new ArrayList();
4.
5. public void addItem(String item){
6. if (!items.contains(item)){
7. items.add(item);
8. }
9. }
10. public void addItem(String item, int position){
11. if (!items.contains(item)){
12. items.add(position, item);
13. }
14. }
15.
16. public void removeItem(String item){
17. if (items.contains(item)){
18. items.remove(items.indexOf(item));
19. }
20. }
21.
22. public boolean supportsOrdering(){
23. return true;
24. }
25.
26. public int getNumberOfItems(){
27. return items.size();
28. }
29.
30. public String getItem(int index){
31. if (index < items.size()){
32. return (String)items.get(index);
33. }
34. return null;
35. }
36. }
The abstraction represents the operations on the list that are available to the outside world. The BaseList class
provides general list capabilities.
Example A.140 BaseList.java
1. public class BaseList{
2. protected ListImpl implementor;
3.
4. public void setImplementor(ListImpl impl){
5. implementor = impl;
6. }
7.
8. public void add(String item){
 
Search WWH ::




Custom Search