We usually write a click handler on a button (in GWT or Swing or Android) in the following way (way 1).
class A {
public void myMethod() {
int count = 0 ;
Button myButton = new Button("x");
myButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
count = 1 ;
}
});
}
}
However, we can also write a different class for the click handler and implement it like the following (way 2) :
class A implements ButtonClickInterface {
int count ;
public void myMethod() {
count = 0 ;
Button myButton = new Button("x");
myButton.addClickHandler(new MyClickHander(this));
}
@Override
public void buttonClicked() {
count = 1 ;
}
}
interface ButtonClickInterface {
public void buttonClicked() ;
}
class MyClickHandler implements ClickHandler {
ButtonClickInterface buttonClickInterface ;
public MyClickHandler(ButtonClickInterface buttonClickInterface) {
this.buttonClickInterface = buttonClickInterface ;
}
@Override
public void onClick(ClickEvent event) {
buttonClickInterface.buttonClicked() ;
}
}
Here I have to make count as a class variable. Can this have any drawbacks? Also can the above way of implementation have any other drawbacks? How would the two ways in which I have implemented the ClickHandler face off against each other in terms of complexity, coupling, number of objects created and code readability ?
Your second solution is way too complex.
I often do that on Android (pseudocode):