如何初始化循环依赖(最终的字段引用对方)? [英] How to initialize a circular dependency (final fields referencing each other)?

查看:185
本文介绍了如何初始化循环依赖(最终的字段引用对方)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何初始化这个:

  class A {
final B b;

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

class B {
final A a;

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

DI框架,反思,更好的设计? >

动机和用例(添加)



我的具体用例是简化字段访问 A B 的子类。所以我注意到他们很快地引用了派生类中的字段,而不需要在每个子类中明确声明。



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

解决方案

您可以使用工厂方法

  class A {
final B b;

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

抽象类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);
}
};
}
}


How do you initialize this:

class A {
    final B b;

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

class B {
    final A a;

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

DI framework, reflection, better design?

Motivation and a use case (added):

My particular use case is simplifying field access in A's and B's sub-classes. So I'm injecting them to shortly reference them by fields in the derived classes without a need to declare explicitly in each sub-class.

There is also a recommendation on DI that objects should better be immutable: Guice best practices and anti-patterns.

解决方案

You could use a factory method

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

这篇关于如何初始化循环依赖(最终的字段引用对方)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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