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

标签 java polymorphism composite

我有一个类似这样的类结构:

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 版本。)因此我的父属性永远不会被设置。

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

  1. 删除 Node 版本的 AttachLeft/Right,只在 Composite 版本中使用 instanceof 和转换
  2. 添加特定于节点的 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/

相关文章:

imagemagick - PythonMagic : How do a composite with a dissolve value?

java - 限制嵌入式 Jetty 中的上传大小

java - 模拟 SWT 打印机

java - MySQL 无法更改正在主动写入的 TABLE

C++ 多态风格 - 仅在子类中实现自定义方法

ffmpeg - 使用 ImageMagick 工具和 ffmpeg 滑动删除效果

java - wicket 1.5 + 错误页面 + 找不到 css 资源的相关路径

java - 如何从父类(super class)调用抽象方法(在子类中重写)?

java - 当我可以通过引用子类访问所有方法时,为什么还要引用基类?

java - Scala中的复合设计模式?