如何保持不变性在两个对象之间具有相互依赖关系 [英] how do I keep immutability having a mutual dependency between 2 objects

查看:223
本文介绍了如何保持不变性在两个对象之间具有相互依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建两个不可变对象时遇到问题,在这两个对象中,两个对象都有依赖关系。问题:如何解决这种情况,使这些对象不可变?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆