-5

所以我正在考虑一个小项目。我似乎遇到的一个问题是:我有一个类 A,它包含一个类 C 的实例和一个类 B 的实例列表。每个类都包含一个计时器。当该计时器触发事件​​时,我需要执行一个 C 类方法。

public class A
{
  C C1 = new C(this);
  public ArrayList<B> B1= new ArrayList<>();        
}

所以当计时器到期时,我需要触发类似的东西:

C1.method()
4

1 回答 1

0

非常基本/简单的方法:实现一个简单的订阅/发布框架。

  1. 创建一个定义回调方法的接口。
  2. 在 C 类中实现回调接口。
  3. 提供一种方法,C 类通过该方法向 B 类的每个实例注册回调;这样做。
  4. 当定时器在 b 类的特定实例中触发时,调用回调。

例如:

public interface BlammyHoot
{
  void hoot(); // this is the call back.
}

public class C implements BlammyHoot
{
  public void hoot()
  {
    // implement the callbe method here.
  }
}

public class B
{
  private List<BlammyHoot> hootList = new LinkedList<BlammyHoot>();

  public void registerBlammyHoot(final BlammyHoot theHoot)
  {
    if (theHoot != null)
    {
      hootList.add(theHoot);
    }
  }

  public void respondToTimerTimeout()
  {
    for (BlammyHoot hootElement : hootList)
    {
      hootElement.hoot();
    }
  }
}

警告:对上述 java 代码执行的零测试(包括但不限于我没有编译它)。

于 2013-01-29T20:06:33.397 回答