动态找到正确的方法以免重复相同的代码

时间:2019-05-15 09:35:15

标签: java design-patterns java-8 refactoring dry

以下代码将侦听器添加到几个SWT Text元素。唯一的区别是Listeners方法中的代码。有没有一种方法可以通过找到正确的动态使用方法来减少此代码的重复性?

在此示例中,使用了FocusListener,但这并不相关。

private void addFocusLostListeners() {
    nameText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setName(nameText.getText());
        }
    });
    ageText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setAge(ageText.getText());
        }
    });
    emailText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setEmail(emailText.getText());
        }
    });
    ...
}

1 个答案:

答案 0 :(得分:4)

您可以创建一个辅助方法(您需要将TextField替换为nameTextageText等实际类):

private static void addFocusListener(TextField field, Consumer<? super String> setter) {
    field.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            setter.accept(field.getText());
        }
    });
}

然后您可以致电:

private void addFocusLostListeners() {
    addFocusListener(nameText, myDataObject::setName);
    addFocusListener(ageText, myDataObject::setAge);
    addFocusListener(emailText, myDataObject::setEmail);
}