Extending the Bridge
Now suppose we need to make some changes in the way these lists display the data. For example, maybe you want to have the products displayed in alphabetical order. You might think you'd need to either modify or subclass both the list and table classes. This can quickly get to be a maintenance nightmare, especially if more than two such displays are needed at some point. Instead, we simply derive a new SortBridge class similar to the ListBridge class.
In order to sort Product objects, we have the Product class implement the IComparable interface, which means it has a CompareTo method.
public class Product : IComparable { private string quantity; private string name; //----- public Product(string line) { int i = line.IndexOf ("--"); name =line.Substring (0, i).Trim (); quantity = line.Substring (i+2).Trim (); } //----- public string getQuantity() { return quantity; } //----- public string getName() { return name; } //----- public int CompareTo(object p) { Product prod =(Product) p; return name.CompareTo (prod.getName ()); }
With that change, sorting of the Product objects is much easier.
public class SortBridge:ListBridge { //----- public SortBridge(VisList v):base(v){ } //----- public override void addData(ArrayList ar) { int max = ar.Count ; Product[] prod = new Product[max]; for(int i=0; i< max ; i++) { prod[i] = (Product)ar[i]; } for(int i=0; i < max ; i++) { for (int j=i; j < max; j++) { if(prod[i].CompareTo (prod[j])>0) { Product pt = prod[i]; prod[i]= prod[j]; prod[j] = pt; } } } for(int i = 0; i< max; i++) { vis.addLine (prod[i]); } } }
You can see the sorted result in Figure 15-3.
Figure 15-3. The sorted list generated using the SortBridge class
This clearly shows that you can vary the interface without changing the implementation. The converse is also true. For example, you could create another type of list display and replace one of the current list displays without any other program changes as long as the new list also implements the VisList interface. Here is the TreeList class.
public class TreeList:VisList { private TreeView tree; private TreeAdapter gAdapter; //----- public TreeList(TreeView tre) { tree = tre; gAdapter = new TreeAdapter (tree); } //----- public void addLine(Product p) { gAdapter.Add (p); }
Note that we take advantage of the TreeAdapter we wrote in the previous chap-ter and modify it to work on Product objects.
public class TreeAdapter { private TreeView tree; //------ public TreeAdapter(TreeView tr) { tree=tr; } //------ public void Add(Product p) { TreeNode nod; //add a root node nod = tree.Nodes.Add(p.getName()); //add a child node to it nod.Nodes.Add(p.getQuantity ()); tree.ExpandAll (); }
In Figure 15-4, we have created a tree list component that implements the VisList interface and replaced the ordinary list without any change in the public interface to the classes.
Figure 15-4. Another display using a Bridge to a tree list