Java classes reference each other

前端 未结 3 1018
执笔经年
执笔经年 2021-01-17 22:18

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


        
3条回答
  •  情书的邮戳
    2021-01-17 23:01

    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.

提交回复
热议问题