解决循环依赖Java

时间:2016-02-01 15:43:25

标签: java dependencies circular-dependency

下面我发布了一个带有循环依赖关系的简单Java代码示例。

MyObject有两个成员(myObject1myObject2),其中包含对象本身的引用。

有没有办法解决依赖关系但保留功能?

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() {
    ...
  }
}

1 个答案:

答案 0 :(得分:1)

声明接口:

public class MyObject implements MyInterface {

实施界面:

MyObject

在包装器和后代中使用接口而不是具体的类public class MyObjectWrapper { private MyInterface myObject; public MyObjectWrapper (MyInterface myObject) { this.myObject = myObject; } public myMethod(int param) { this.myObject.myMethod(param); } }

RotateAnimation animation = 
    new RotateAnimation(
        mCurrentAngle,
        toAngle,
        Animation.RELATIVE_TO_SELF,
        pivotX,
        Animation.RELATIVE_TO_SELF, 
        pivotY);

animation.setRepeatCount(0);
animation.setFillAfter(true);
animation.setFillEnabled(true);
animation.setInterpolator(new OvershootInterpolator());
animation.setDuration(duration);
mMeterPointer.startAnimation(animation);