我有一个类似这样的类结构:
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)
不幸的是,由于静态绑定(bind),attachLeft/Right(Node c) 方法永远不会被 AttachRandomly 调用。 (attachRandomly 正在获取 Composite,因此始终会调用 AttachLeft/Right 的 Composite 版本。)因此我的父属性永远不会被设置。
现在,我可以想出几种方法来完成这项工作:
- 删除 Node 版本的 AttachLeft/Right,只在 Composite 版本中使用 instanceof 和转换
- 添加特定于节点的 AttachRandomly 版本
选项 1 感觉很糟糕(instanceof!casting!),而选项 2 由于额外的代码量而感觉很尴尬。有没有更好的方法来做到这一点,以便多态性可以发挥作用并帮助我?
最佳答案
你可以这样写。这个基本思想称为双重调度。它为每个方法调用引入了新的分派(dispatch)级别,以允许使用动态绑定(bind)。
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.
}
}
关于Java 静态绑定(bind)使得实现 Composite 变得很尴尬,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48709175/