Answer the question
In order to leave comments, you need to log in
Should I use instanceof if there are several different objects in the JTree?
There are several different types of objects in my JTree tree (6 pieces).
Different objects require completely different methods to work.
Each class has about a dozen of its fields.
<code lang="java">
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getModel().getChild(currentNode, i);
Object ob = node.getUserObject();
if(ob instanceof DescriptionTemplate) {
// todo...
}
</code>
Answer the question
In order to leave comments, you need to log in
How justified is the use of the instanceof operator in this case?This is mistake.
Do not forget about the possibility of using strategies.
Very approximate code, but the essence is clear:
private static final Map<Class, Action> strategies = new HashMap<>();
private static interface Action {
void doAction(Params params);
}
static {
strategies.put(ANodeType.class, new Action() {
public void doAction(Params params){
...
}
});
strategies.put(BNodeType.class, new Action() {
public void doAction(Params params){
...
}
});
}
...
public void handleTreeNode(Object node, Params params){
strategies.get(node.getClass()).doAction(params);
}
public void handleTreeNode(JTreeNode node, Params params){
node.doAction(params);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question