Interfaces and Collection Classes in Delphi
By Ray Lischner, December 01, 2001
Delphi has been traditionally weak when it comes to collections. Using interfaces, it is now possible to write useful, type-safe collection classes in Delphi. Ray examines an interface-based set of Collection classes and provides a red-black tree implementation as an example.
December 2001/Interfaces and Collection Classes in Delphi
Example 5: Constructing the tree view representation of the red-black tree
// Debug a red-black tree by showing the internal tree structure.
// Visibly display an image for red and black nodes. To help color-blind
// users, Red nodes have a Round icon and Black nodes have a Box icon.
// Let the debug form access protected methods and properties.
type
TExposeTree = class(TRbTree)
end;
TExposeNode = class(TRbNode)
end;
// Refresh the tree display after changing the tree.
procedure TTreeForm.RefreshTree;
procedure WalkTree(RbNode: TRbNode; ViewNode: TTreeNode);
var
Item: ICollectible;
Assoc: IAssociation;
begin
if RbNode <> TExposeTree(Tree).Leaf then
begin
// Get the string item from the node. If the collection is a map,
// the node holds an association, and the string is the key.
Item := TExposeNode(RbNode).Item;
if Item.QueryInterface(IAssociation, Assoc) = S_OK then
Assoc.GetKey(Item);
ViewNode := TreeView.Items.AddChild(ViewNode, (Item as IString).Value);
if TExposeNode(RbNode).IsRed then
ViewNode.ImageIndex := 0
else
ViewNode.ImageIndex := 1;
ViewNode.SelectedIndex := ViewNode.ImageIndex;
WalkTree(TExposeNode(RbNode).Left, ViewNode);
WalkTree(TExposeNode(RbNode).Right, ViewNode);
end;
end;
begin
TreeView.Items.BeginUpdate;
try
TreeView.Items.Clear;
WalkTree(TExposeTree(Tree).Root, nil);
TreeView.FullExpand;
finally
TreeView.Items.EndUpdate;
end;
end;