如何初始化循环依赖(最终字段相互引用)?

And*_*hev 6 java reflection design-patterns dependency-injection guice

你如何初始化这个:

class A {
    final B b;

    A(B b) {
        this.b = b;
    }
}

class B {
    final A a;

    B(A a) {
        this.a = a;
    }
}
Run Code Online (Sandbox Code Playgroud)

DI框架,反射,更好的设计?

动机和用例(已添加):

我的特殊用例是简化A's和B子类中的字段访问.所以我注入它们很快就会通过派生类中的字段引用它们,而不需要在每个子类中显式声明.

关于DI的建议还有一个对象应该是不可改变的:Guice最佳实践和反模式.

Mat*_*igh 6

您可以使用工厂方法

class A {
    final B b;

    A(B b) {
        this.b = b;
    }
}

abstract class B {
    final A a;

    B() {
        this.a = constructA();
    }

    protected abstract A constructA();
}

public class C {
    public static void main(String []args){
        new B(){
            protected A constructA(){
                return new A(this);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)