我目前正在尝试重构我的代码后,我读到的实现优先于扩展。目前,我正在尝试创建一个将对象添加到场景的功能。为了更好地确定每个对象是什么,有多种解释,如用于更新,渲染列表等Java“instanceof”添加多个列表
private List<Updatable> updatables;
private List<Removable> removables;
private List<Renderable> renderables;
private List<Collidable> collidables;
我想打一个函数到我的Scene类,像这样:
public void add(Object o) {
if(o instanceof Updatable)
updatables.add((Updatable) o);
if(o instanceof Removable)
removables.add((Removable) o);
if(o instanceof Renderable)
renderables.add((Renderable) o);
if(o instanceof Collidable)
collidables.add((Collidable) o);
}
同样,我会创建一个类似的删除功能。我的问题是,如果这是不好的编码习惯,因为我听说过instanceof的缺陷,其次,如果是这样,是否有办法绕过/重构我的代码以使添加实例变得简单?我更喜欢不必为每个列表添加一个实例,并且每次都定义它属于哪个实例。
很多类似的问题。 [例如](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+instanceof+code+smell) –