0

因此,我一直在开发一个应用程序,该应用程序具有具有许多不同输入和输出的 Plan 模型,并且应用程序的布局具有用于输入的滑块控件和用于输出的标签。当输入发生变化时,它会更新模型,然后运行计算,然后更新视图。一开始我并没有觉得这个架构有什么问题,但是即使是简单的计算也似乎运行得很慢,阻塞了 UI 线程。当然,我确实有一种有点复杂的更新方式:

  1. 滑块(在视图组子类中)更新其值并向委托(实现特定于该视图组子类的接口)发送消息。
  2. 委托(持有模型和控制子视图)告诉计划实例设置一个新值,这会触发计划重新计算其输出。
  3. 一旦计划完成计算,它会向委托发送另一条消息,然后委托其输出视图使用新值进行更新。

我已经根据我开发的 iOS 应用程序对这种架构进行了建模,该应用程序在运行计算时似乎没有那么大的问题。

现在,我知道 Android 与 iOS 有很大不同,所以我想知道我是否完全错了。有没有办法让这些视图观察 Plan 模型的变化,然后获取它应该显示的值?

我在这里看到的另一个主要问题是滑块输入。如果我将模型更新计算放到一个线程中,每次滑块改变时,都会创建一个新线程。这些线程(如我所见)将或多或少地以随机顺序完成,当您应该看到增量更改时,以这样的方式更新视图也毫无意义。是否有一种很好的线程计算方法应该可以通过搜索栏进行更改?

4

2 回答 2

1

你看过ObserverObservable吗?也许您观察到的模型可以使用Runnable执行更新,然后通知观察者。

于 2011-11-30T22:19:42.233 回答
0

这只是我脑海中的一个想法:

您可以实现某种Queue.

你需要 a 来Thread运行,它包含Queue.

public class QueueThread extends Thread {
  private boolean running;
  private ArrayDeque<Runnable> queue;
  private Thread current;

  public QueueThread() {
    running = true;
    queue = new ArrayDeque<Runnable>();
    current = new Thread();
  }

  @Override
  public void run() {
    while( running ) {
      if( !queue.isEmpty() && !current.isAlive() ) { //We only want to start a new thread if there is one or more in the queue AND the old task is not runnning.
        current = new Thread( queue.pollFirst() );
        current.start();
      }
      else
        try {
          Thread.sleep( 200 ); //We need a sleep in order to not hammer the CPU.
        }
        catch( InterruptedException e ) {
          e.printStackTrace();
        }
    }
  }

  public void stopThread() {
    running = false;
  }

  public void add( Runnable task ) {
    queue.addLast( task ); //Here is where we add a task to the queue. The slider (or whoever posts the updates) must have a reference to this thread object.
  }
}

这样做将允许每次更新在下一次开始之前完成。我不确定它在性能方面的表现如何。我没有测试过它或任何东西。这只是一个想法。

于 2011-12-01T14:59:26.620 回答