Circular dependency in java classes

后端 未结 5 1932
误落风尘
误落风尘 2020-11-28 09:23

I have the following classes.

public class B 
{
    public A a;

    public B()
    {
        a= new A();
        System.out.println(\"Creating B\");
    }
         


        
5条回答
  •  爱一瞬间的悲伤
    2020-11-28 09:56

    A similar workaround to getters/setters using composition and and constructor injection for the dependencies. The big thing to note is that the objects don't create the instance to the other classes, they are passed in (aka injection).

    public interface A {}
    public interface B {}
    
    public class AProxy implements A {
        private A delegate;
    
        public void setDelegate(A a) {
            delegate = a;
        }
    
        // Any implementation methods delegate to 'delegate'
        // public void doStuff() { delegate.doStuff() }
    }
    
    public class AImpl implements A {
        private final B b;
    
        AImpl(B b) {
            this.b = b;
        }
    }
    
    public class BImpl implements B {
        private final A a;
    
        BImpl(A a) {
            this.a = a;
        }
    }
    
    public static void main(String[] args) {
        A proxy = new AProxy();
        B b = new BImpl(proxy);
        A a = new AImpl(b);
        proxy.setDelegate(a);
    }
    

提交回复
热议问题