简体   繁体   English

如何保持2个对象之间具有相互依赖性的不变性

[英]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. 我在创建2个不可变对象时遇到问题,它们两个都相互依赖。 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. 然后,您可能需要考虑将某种保护逻辑(Exceptions)放入Another.setOne()中,以便只能将One对象设置一次。

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() 还请考虑您可能会在使用默认构造函数实例化Another而不初始化one变量的情况下遇到问题,在这种情况下,您可能必须删除readonly属性并在setOne()中使用上述逻辑

OR 要么

You could create the One class and internally have it create the Another class with a reference to One . 您可以创建One类,并在内部使用对One的引用来创建Another类。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM