2014-05-16 69 views
2

我在閱讀文檔的class Task調用任務的的UpdateProgress

final Task<Void> task = new Task<Void>() { 
     @Override public Void call() { 
      for(int i=0;i<datesAndStudies.length;i++){ 
       updateProgress(i,datesAndStudies.length); 
       DoSomething something = new DoSomething(); 
       something.VeryLongAndTimeConsumingMethod(i); 
      } 
      return null; 
     } 
    }; 

而且我注意到的UpdateProgress保護和workdone/TOTALWORK都被定義爲公衆最終ReadOnlyDoubleProperty

有什麼辦法/解決方法更新/調用的UpdateProgress或編輯從方法這些值(workdone/TOTALWORK):VeryLongAndTimeConsumingMethod(int i)以在類DoSomething的?

回答

3

即使updateProgress(...)是公開的,你必須向Task的引用傳遞給您的DoSomething類,這帶來了一些真醜耦合。如果你有你的Task實現和您的DoSomething類之間的耦合的這個水平,你可能也只是定義了長,時間在Task子類本身消耗的方法,並擺脫其他類:

final Task<Void> task = new Task<Void>() { 
    @Override 
    public Void call() { 
     for (int i=0; i<datesAndStudies.length; i++) { 
      veryLongAndTimeConsumingMethod(i); 
     } 
     return null ; 
    } 

    private void veryLongAndTimeConsumingMethod(int i) { 
     // do whatever... 
     updateProgress(...); 
    } 
}; 

要保護你的脫鉤,只是定義代表DoSomething的進展DoubleProperty,並從Task觀察它,稱updateProgress(...)當它改變:

public class DoSomething { 
    private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper(this, "progress"); 
    public double getProgress() { 
     return progress.get(); 
    } 
    public ReadOnlyDoubleProperty progressProperty() { 
     return progress.getReadOnlyProperty(); 
    } 
    public void veryLongAndTimeConsumingMethod(int i) { 
     // .. 
     progress.set(...); 
    } 
} 

然後:

final Task<Void> task = new Task<>() { 
    @Override 
    public Void call() { 
     for (int i=0; i<datesAndStudies.length; i++) { 
      DoSomething something = new DoSomething(); 
      something.progressProperty().addListener(
       (obs, oldProgress, newProgress) -> updateProgress(...)); 
      something.veryLongAndTimeConsumingMethod(); 
     } 
    } 
}