How to get rid of instanceof in this Builder implementation

拟墨画扇 提交于 2019-12-05 11:02:46

This looks like a classic double-dispatch or visitor scenario. From the double-dispatch reference:

a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call

The Parameter and the CommandBuilder need to interact between themselves on what to do.

The CommandBuilder can call back on the parameter. The Parameter objects all implement a common interface and the implementation of each subclass will differ.

public CommandBuilder append(Parameter p) {
   // the append method called depends on the underlying type of 'p'
   p.append(this);
}

I would add a visitor method to your interface

interface Parameter {
    public void append(CommandBuilder builder);
}

class CommandBuilder {
    public CommandBuilder append(Parameter p) {
       p.append(this);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!