在兩個不同的類中,我具有相同的代碼,如下所示。這部分代碼使我能夠在用戶關閉窗口時添加一個警報屏幕。避免兩次寫同一個東西的最好方法是什麼?消除不同類別中的重複代碼
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();
}
}
});
}
小提示:對於這個項目,我必須使用模型視圖主持人。
提取方法重構:HTTPS: //refactoring.guru/smells/duplicate-code –
如果它不在同一個類中:https://refactoring.com/catalog/replaceMethodWithMethodObject.html –
您的兩個類是否共享一個可以修改的公共超類?如果是這樣,請將功能放在一個方法中,並從子類中調用它。 –