0

Below I posted a simple Java code example with circular dependencies.

MyObject has two members (myObject1 and myObject2) that have a reference to the object itself.

Is there a way to resolve the dependencies but keep the functionality?

public abstract class AbstractMyObject {

   public void myMethod(int param) { 
       System.out.println(param);
   }
}

public class MyObject extends AbstractMyObject  {

   private MyObject1 myObject1;
   private MyObject2 myObject2;

   public MyObject() {
        myObject1 = new MyObject1( this );
        myObject2 = new MyObject2( this );
        ...
   }

   private void aMethod() {
      myObject1.doSomething();
      myObject2.doSomething();
   }
}

public class MyObjectWrapper { 
   private MyObject myObject;

   public MyObjectWrapper (MyObject myObject) {
       this.myObject = myObject;
   }

   public void myMethod(int param) {
     this.myObject.myMethod(param);
   }
}

public class MyObject1 extends MyObjectWrapper {

  public MyObject1(MyObject myObject) {
     super(myObject);
  } 

  private void aMethod() {
    myMethod(1);
  }

  public void doSomething() {
    ...
  }
}

public class MyObject2 extends MyObjectWrapper {

  public MyObject2(MyObject myObject) {
     super(myObject);
  } 

  private void aMethod() {
    myMethod(2);  
  }

  public void doSomething() {
    ...
  }
}
nafets
  • 19
  • 2

1 Answers1

1

Declare interface:

public interface class MyInterface {    
    void myMethod(int param);
}

Implement interface:

public class MyObject implements MyInterface {

Use interface in wrapper and descendants instead of concrete class MyObject:

public class MyObjectWrapper { 
   private MyInterface myObject;

   public MyObjectWrapper (MyInterface myObject) {
       this.myObject = myObject;
   }

   public myMethod(int param) {
     this.myObject.myMethod(param);
   }
}
weston
  • 54,145
  • 21
  • 145
  • 203
  • But this is just kind of more abstraction or? The easiest solution might be to have all the code in just one class, but this makes the class quite huge. So whats the best way to lay out code? – tellob Feb 01 '16 at 15:55
  • 2
    This is just a way to stop class A referencing class B and class B referencing class A. Beyond that I don't know what is best for you I can't see what you are trying to achieve. – weston Feb 01 '16 at 16:19