I am having a problem with creating 2 immutable objects where both of them have a dependency on each other. Question: How do I solve this situation keeping these objects immutable?
public class One
{
private readonly Another another;
public One(Another another)
{
this.another = another;
}
}
public class Another
{
private readonly One one;
public Another(One one)
{
this.one = one;
}
}
Its not possible to do what you suggest, unless you at least allow for dependency injection on one of the classes, as follows:
public class One
{
private readonly Another another;
public One(Another another)
{
this.another = another;
}
}
public class Another
{
private readonly One one;
public Another(One one)
{
this.one = one;
}
public Another() {}
public setOne(One one)
{
this.one = one;
}
}
You may then have to consider putting some sort of protection logic (Exceptions?) in Another.setOne() so that the One object can only be set once.
Also consider that you may have problems instantiating Another
using the default constructor without initializing the one
variable, in which case you may have to remove the readonly attribute and use the aforementioned logic in setOne()
OR
You could create the One
class and internally have it create the Another
class with a reference to One
. This might increase the coupling between the two, but would do what you need, as folows:
public class One
{
private readonly Another another;
public One()
{
this.another = new Another(this);
}
public Another getAnother()
{
return this.another;
}
}
public class Another
{
private readonly One one;
public Another(One one)
{
this.one = one;
}
public Another() {}
}
...
One one = new One();
Another another = one.getAnother();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.