我找到了一个解决方案,虽然它可能不是最好的......
BinaryTreeNode.java:
public void inOrderTraversalFrom(BinaryTreeNode rootNode, BinaryTreeActions actions)
{
if(rootNode.left != null)
inOrderTraversalFrom(rootNode.left, actions);
if(actions != null)
actions.Perform(rootNode);
if(rootNode.right != null)
inOrderTraversalFrom(rootNode.right, actions);
}
BinaryTreeActions.java:
public interface BinaryTreeActions {
public void Perform(BinaryTreeNode node);
}
BinaryTreeGraphicsActions.java:
public interface BinaryTreeGraphicsActions extends BinaryTreeActions {
void DrawNode(BinaryTreeNode node, Graphics g);
}
BinaryTreeView.java:
private void DrawNodes(final Graphics graphics)
{
BinaryTreeNode node = root;
root.inOrderTraversalFrom(node, new BinaryTreeGraphicsActions() {
@Override
public void DrawNode(BinaryTreeNode node, Graphics g) {
// draw the node
}
@Override
public void Perform(BinaryTreeNode node) {
DrawNode(node, graphics);
}
});
}
...并且任何时候你需要一组新的动作,你会为它创建一个新的界面,遵循同样的BinaryTreeGraphicsActions
想法BinaryTreeView
。这允许您执行任何一组操作,具体取决于您为它们设计的界面。
#EDIT: 在发现不需要 for 后,我接受了类似的答案BinaryTreeGraphicsActions
,因为您可以像这样简单地使用BinaryTreeActions执行相同的内联代码:
private void DrawNodes(final Graphics graphics)
{
BinaryTreeNode node = root;
root.inOrderTraversalFrom(node, new BinaryTreeActions() {
@Override
public void Perform(BinaryTreeNode node) {
/* draw the node, using any local vars (providing they are final) */
}
});
}