In most of my java applications, I have a Controller (Logic) class and a GUI class. I usually need the Logic class to call methods on the GUI class, and vice versa. Now, when the Logic constructs the GUI, I pass a reference to “this” in the constructor so the GUI can call methods on the Logic. Here is some example code.
public class Logic {
private int num = 2;
private final GUI gui;
public Logic(){
gui = new GUI(this);
}
public int getNum(){
return num;
}
}
public class GUI {
private final Logic logic;
public GUI(Logic logic){
this.logic = logic;
}
public void calledLater(){
int num = logic.getNum();
}
}
My question is: Is this the best OO way to create an aggregation relationship, or am I messing up my design?
Passing
thisto a UI class is not in itself a problem, as long as the methods of the class are not called throughthis, as in your example. You callgetNumright in the constructor of theGUI, which should be avoided: yourLogicclass may not be ready to return the correct result.One thing to note is that you couple your
GUIto theLogicclass, which may be too much coupling. You should consider extracting an interface fromLogic, and letGUIinteract only with what’s intended for it: