Java 静态绑定使得实现 Composite 变得很尴尬

Java static binding is making it awkward to implement a Composite

我有一个 class 结构是这样的:

interface Composite {}

class Leaf implements Composite { public String val; }

class Node implements Composite {
    private Node parent;
    private Composite left;
    private Composite right;

    public void attachLeft(Composite c) {
         left = c;
    }
    public void attachRight(Composite c) {
         right = c;
    } 
    public void attachLeft(Node n) {
         left = n;
         n.parent = this;
    }
    public void attachRight(Node n) {
         right = n;
         n.parent = this;
    }
    public void attachRandomly(Composite c) {
         if ( ThreadLocalRandom.current().nextBoolean() ) {
             attachRight(c);
         } else {
             attachLeft(c);
         }
    }
}

我有一个生成随机树的方法(伪代码):

// build tree
for some number of nodes :
    make newNode
    oldNode = randomly pick an existing node with an empty right/left 
    oldNode.attachRandomly(newNode)

// fill leaves of tree
for each node with empty right/left :
    while node has empty right/left :
        node.attachRandomly(new Leaf)

不幸的是,由于静态绑定,attachLeft/Right(Node c) 方法永远不会被 attachRandomly 调用。 (attachRandomly 正在获取一个 Composite,因此 attachLeft/Right 的 Composite 版本总是被调用。)所以我的父属性永远不会被设置。

现在,我可以想出几种方法来完成这项工作:

  1. 删除 attachLeft/Right 的 Node 版本,只使用 instanceof 并在 Composite 版本中进行转换
  2. 添加特定于节点的 attachRandomly 版本

选项 1 令人讨厌(instanceof!强制转换!)而选项 2 只是因为额外的代码量而感到尴尬。有没有更好的方法来做到这一点,以便多态性可以发挥作用并帮助我解决这个问题?

你可以这样写。这个基本思想叫做double dispatching。它为您的每个方法调用引入了新级别的调度,以允许使用动态绑定。

interface Composite {
    void attachToLeft(Node newParent);
    void attachToRight(Node newParent);
}

class Leaf implements Composite { 
    public String val;
    @Override
    public void attachToLeft(Node newParent) {
        newParent.left = this;
    }
    @Override
    public void attachToRight(Node newParent) {
        newParent.right = this;
    }
}

class Node implements Composite {
    private Node parent;
    private Composite left;
    private Composite right;

    public void attachLeft(Composite c) {
         c.attachToLeft(this);
    }
    public void attachRight(Composite c) {
         c.attachToRight(this);
    } 
    @Override
    public void attachToLeft(Node newParent) {
         this.parent = newParent;
         newParent.left = this;
    }
    @Override
    public void attachToRight(Node newParent) {
         this.parent = newParent;
         newParent.right = this.
    }
}