Java Reference
In-Depth Information
9. implementor.addItem(item);
10. }
11. public void add(String item, int position){
12. if (implementor.supportsOrdering()){
13. implementor.addItem(item, position);
14. }
15. }
16.
17. public void remove(String item){
18. implementor.removeItem(item);
19. }
20.
21. public String get(int index){
22. return implementor.getItem(index);
23. }
24.
25. public int count(){
26. return implementor.getNumberOfItems();
27. }
28. }
Note that all the operations are delegated to the implementer variable, which represents the list implementation.
Whenever operations are requested of the List , they are actually delegated “across the bridge” to the associated
ListImpl object.
It's easy to extend the features provided by the BaseList —you subclass the BaseList and add additional
functionality. The NumberedList class demonstrates the power of the Bridge; by overriding the get method, the
class is able to provide numbering of the items on the list.
Example A.141 NumberedList.java
1. public class NumberedList extends BaseList{
2. public String get(int index){
3. return (index + 1) + ". " + super.get(index);
4. }
5. }
The OrnamentedList class shows another abstraction. In this case, the extension allows each list item to be
prepended with a designated symbol, such as an asterisk or other character.
Example A.142 OrnamentedList.java
1. public class OrnamentedList extends BaseList{
2. private char itemType;
3.
4. public char getItemType(){ return itemType; }
5. public void setItemType(char newItemType){
6. if (newItemType > ' '){
7. itemType = newItemType;
8. }
9. }
10.
11. public String get(int index){
12. return itemType + " " + super.get(index);
13. }
14. }
RunPattern demonstrates this example in action. The main method creates an OrderedListImpl object and
populates it with items. Next, it associates the implementation with three different abstraction objects, and prints
the list contents. This illustrates two important principles: that the same implementation can be used with multiple
abstractions, and that each abstraction can modify the appearance of the underlying data.
Example A.143 RunPattern.java
1. public class RunPattern{
2. public static void main(String [] arguments){
3. System.out.println("Example for the Bridge pattern");
4. System.out.println();
5. System.out.println("This example divides complex behavior among two");
6. System.out.println(" classes - the abstraction and the implementation.");
7. System.out.println();
8. System.out.println("In this case, there are two classes which can provide the");
9. System.out.println(" abstraction - BaseList and OrnamentedList. The BaseList");
10. System.out.println(" provides core funtionality, while the OrnamentedList");
11. System.out.println(" expands on the model by adding a list character.");
Search WWH ::




Custom Search