2017-02-23 29 views
1

在兩個不同的類中,我具有相同的代碼,如下所示。這部分代碼使我能夠在用戶關閉窗口時添加一個警報屏幕。避免兩次寫同一個東西的最好方法是什麼?消除不同類別中的重複代碼

public void addWindowEventHandlers() { 
    view.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() { 
     @Override 
     public void handle(WindowEvent event) { 
      Alert alert = new Alert(Alert.AlertType.CONFIRMATION); 
      alert.setHeaderText("You are about to exit the game."); 
      alert.setContentText("Are you sure?"); 
      alert.setTitle("Warning"); 
      alert.getButtonTypes().clear(); 
      ButtonType no = new ButtonType("No"); 
      ButtonType yes = new ButtonType("Yes"); 
      alert.getButtonTypes().addAll(no, yes); 
      alert.showAndWait(); 
      if (alert.getResult() == null || alert.getResult().equals(no)) { 
       event.consume(); 
      } 
     } 
    }); 
} 

小提示:對於這個項目,我必須使用模型視圖主持人。

+1

提取方法重構:HTTPS: //refactoring.guru/smells/duplicate-code –

+1

如果它不在同一個類中:https://refactoring.com/catalog/replaceMethodWithMethodObject.html –

+0

您的兩個類是否共享一個可以修改的公共超類?如果是這樣,請將功能放在一個方法中,並從子類中調用它。 –

回答

1

爲什麼不只是使處理一個獨立的類(或公共靜態內部類中其他一些方便類):

public class CloseWindowConfirmation implements EventHandler<WindowEvent>() { 
    @Override 
    public void handle(WindowEvent event) { 
     Alert alert = new Alert(Alert.AlertType.CONFIRMATION); 
     alert.setHeaderText("You are about to exit the game."); 
     alert.setContentText("Are you sure?"); 
     alert.setTitle("Warning"); 
     alert.getButtonTypes().clear(); 
     ButtonType no = new ButtonType("No"); 
     ButtonType yes = new ButtonType("Yes"); 
     alert.getButtonTypes().addAll(no, yes); 
     alert.showAndWait(); 
     if (alert.getResult() == null || alert.getResult().equals(no)) { 
      event.consume(); 
     } 
    } 
} 

然後你只需做

public void addWindowEventHandlers() { 
    view.getScene().getWindow().setOnCloseRequest(new CloseWindowConfirmation()); 
} 
+0

謝謝@James_D;)還有一個問題,如何提取一個方法,如果它有變量呢?像: if(alert.getResult()。equals(yes)){ view.getTextField(); view.getScene()。getWindow()。hide(); } – m4t5k4

+0

只需在處理程序類中創建需要屬性的值並將其傳遞給構造函數。 –