消除不同 类 中的重复代码

Eliminate duplicated code in different classes

在两个不同的 类 中,我有如下相同的代码。这部分代码使我能够在用户关闭 window 时添加一个警告屏幕。避免重复编写相同内容的最佳方法是什么?

    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();
            }
        }
    });
}

注意事项:对于这个项目,我必须使用模型视图展示器。

为什么不让处理程序成为一个独立的 class(或者 public 静态内部 class 在一些其他方便的 class):

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());
}