如何保持不变性在两个对象之间具有相互依赖关系 [英] how do I keep immutability having a mutual dependency between 2 objects
问题描述
我在创建两个不可变对象时遇到问题,在这两个对象中,两个对象都有依赖关系。问题:如何解决这种情况,使这些对象不可变?
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;
}
}
然后您可能需要考虑采取某种保护措施在Another.setOne()中的逻辑(异常?),以便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.
还要考虑到您可能会在实例化另一个
使用默认构造函数,而不初始化一个
变量,在这种情况下,您可能必须删除readonly属性并在setOne中使用上述逻辑()
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
您可以创建一个
类,并在内部创建一个引用 One
的另一个
类。这可能会增加两者之间的耦合,但会做你所需要的,如下所示:
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();
这篇关于如何保持不变性在两个对象之间具有相互依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!