I am trying to create a decent looking solution for a problem I have. I can explain in words, but the code will be clearer:
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(ClassA.getButtonOne()) ||
e.getSource().equals(ClassB.getButtonOne())) {
???????.setEnabled(false); (class a or class b)
}
Explanation: How can I change e.getSource() into the right class type, so I can perform methods on it? One extra detail: I am sure all methods in the if-statement possess the method I want to execute, in the example above ‘setEnabled’. I can solve the problem by creating multiple if-statements, but that would create duplicate code (especially since there will also be a class C and D in the future) .
If you need to use the same listener, the requirement looks like a visitor or double-dispatch pattern. You should redirect back onto the source class e.g.
This way you don’t have to implement lots of ‘if’s (which is error prone and verbose, as you’ve identified). You simply check the object type upon event receipt, and call back on it if appropriate. Note that I call back in the above with the event and the object receiving the event. You can choose, however, which parameters are important/relevant.