重构树的递归修改

时间:2013-06-04 17:34:41

标签: java recursion refactoring tree-traversal

如何重构以下代码:

class ModifyTree{
    public void doActionsOnTree(Tree tree) {
        rAction1(tree.getRoot());
        rAction2(tree.getRoot());
    }

    private void action1(Node node) {
        // do something with node;
    }

    private void action2 (Node node) {
        // do something with node
    }

    private void rAction1(Node node) {
        action1(node);
        for(Node nodeIterator : node.getChildren())
            rAction1(nodeIterator);
    }

    private void rAction2(Node node) {
        action2(node);
        for(Node nodeIterator : node.getChildren())
            rAction2(nodeIterator);
    }
}

方法rAction1()rAction2()看起来非常相似。在这种情况下,有没有办法不重复代码?

2 个答案:

答案 0 :(得分:3)

您可以使用Visitior pattern

interface NodeHandler {
    public void handleNode(Node node);
}

class ModifyTree{
    private void handleNodeAndChildren(NodeHandler nodeHandler, Node node) {
        nodeHandler.handleNode(node);
        for(Node child : node.getChildren()) 
            handleNodeAndChildren(nodeHandler, child);
        }
    }

    public void doActionsOnTree(Tree tree) {
        handleNodeAndChildren(new NodeHandler() { public void handlNode(Node n) {/* code for raction1 goes here*/}}, tree.getRoot());
        handleNodeAndChildren(new NodeHandler() { public void handlNode(Node n) {/* code for raction2 goes here*/}}, tree.getRoot());
    }
}

答案 1 :(得分:1)

您可以将action1action2转换为对象:

interface Action {
    void doAction(Node node);
}
Action action1 = new Action() {
    @Override
    public void doAction(Node node) {
        // what used to be the body of action1()
    }
}
Action action2 = new Action() {
    @Override
    public void doAction(Node node) {
        // what used to be the body of action2()
    }
}

然后你可以编写一个递归方法:

private void rAction(Action action, Node node) {
    action.doAction(node);
    for (Node child : node.getChildren()) {
        rAction(action, child);
    }
}

有关此想法的更一般版本,请查看visitor pattern