Reputation: 1092
I have a composition relationship as follows. SubClass uses a method of MainClass. So it needs the reference of MainClass. Doing like that, SubClass
is strongly tied to MainClass
. Is it advisable to do so? Is there a way/design pattern to break cross dependency?
Public Class MainClass {
private SubClass subClass;
public MainClass(){
subClass=new SubClass(this);
}
public doTCPCall(){
....
}
}
Public Class SubClass {
private MainClass mainClass;
public SubClass(MainClass mainClass){
this.mainClass=mainClass;
}
public doTCPCall(){
mainClass.doTCPCall();
}
}
Upvotes: 0
Views: 58
Reputation: 9049
If the method MainClass.doTCPcall()
does not depend on any specific MainClass
instance information to run, it could be made static
. This way, SubClass
would not need to store an instance of MainClass
. It could just call the static method:
public void doTCPCall() {
// Call the doTCPCall() using the class name instead of an instance
MainClass.doTCPCall();
}
Upvotes: 1