I need to link an object of type B to any instance of type A (circular dependencies). I could also declare another method, which must be called after the constructor of A and link a new B to an A-instance. What I want to achieve is not having to call such a method manually. This is the sample code:
public Class A{
B b;
public A(){
b = new B(this); // this does not work,
// as this references an object that has not been created yet
}
}
public Class B{
A a;
public B(A a){
this.a = a; //or something else
}
}
I commented the problematic line. I also understand why it can't work. What I need to know is, if there is a well-known design pattern to avoid this problematic? Or should I just redesign my class model, putting anything in B to A? Any suggestions?
It does work. It's problematic in that it exposes an object before it's been fully initialized (so if the B constructor calls methods on the parameter, for example, that could be a bad thing), but it does work. The reference B.a will be a reference to the instance of A that's been/being constructed.
I would recommend trying to avoid the cyclic reference where possible, but where the alternative is even worse, the code you've given will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With