Java类彼此引用 [英] Java classes reference each other

查看:148
本文介绍了Java类彼此引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个java类文件。每一个都有另一个使用的方法。

  public class class1 {
class2 c2 = new class2
m1(){
c2.ma();
m2();
}
m2(){}
}

public class class2 {
class1 c1 = new class1();
ma(){}
mb(){
c1.m2();
}
}

  class1 c1 = new class1(); 

  class2 c2 = new class2(); 

引用一个无限循环,导致java.lang.StackOverflowError错误。 p>

有没有一些方法让类引用彼此,或者我别无选择,只能将我的所有方法转换成一个类?

解决方案

如上所述,这是代码气味的标志。





尽管使用一个依赖框架如Spring可以帮助解决这个问题上面的问题,如果你使用构造函数注入,那么你不能有循环依赖性!但是至少当一个bean注入时,你确定它不是一半构造的。



如果你不想使用依赖注入框架,考虑一个工厂模式其中两个对象都由工厂方法创建,它返回一个包含完全构造的对象的元组(或在Java中没有对元组的本地支持的容器对象)。


I have two java class files. Each of them has methods the other one uses.

public class class1{
    class2 c2 = new class2(); 
    m1(){
        c2.ma(); 
        m2();
    }
    m2(){}
}

public class class2{
    class1 c1 = new class1();
    ma(){}
    mb(){
        c1.m2();
    }
}

The lines

class1 c1 = new class1();  

and

class2 c2 = new class2();  

refer to each other causing an infinite loop, resulting in a java.lang.StackOverflowError error.

Is there some way to have the classes refer to each other or do I have no choice but to transfer all of my methods into a single class?

解决方案

As is said above, this is a sign of code smell.

Having a setter to set the method afterwards is not satisfactory, as you have an object in an indeterminate state, until the setters are called.

Although using a dependency framework such as Spring can help solve the above problem, if you use constructor injection, then you cannot have cyclic dependencies either! But at least when a bean is injected, you are sure it is not half constructed.

If you don't want to use a dependency injection framework, consider a factory pattern where both objects are created by a factory method, which returns a tuple (or a container object in the case of Java which has no native support for tuples) containing the fully constructed objects.

这篇关于Java类彼此引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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