1

我在创建 2 个不可变对象时遇到问题,它们都相互依赖。问题:如何解决这种情况,保持这些对象不可变?

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;
    }
}
4

1 回答 1

1

除非您至少允许对其中一个类进行依赖注入,否则不可能按照您的建议进行操作,如下所示:

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 对象只能设置一次。

还要考虑到Another在没有初始化变量的情况下使用默认构造函数进行实例化时可能会遇到问题one,在这种情况下,您可能必须删除 readonly 属性并在 setOne() 中使用上述逻辑

或者

您可以创建One该类并在内部让它Another使用对One. 这可能会增加两者之间的耦合,但会做你需要的,如下所示:

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();
于 2012-05-17T05:52:56.933 回答