动态找到正确的方法以避免重复相同的代码
Dynamically find the correct method in order to not repeat the same code
以下代码将侦听器添加到多个 SWT 文本元素。唯一的区别是 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());
}
});
...
}
你可以制作一个辅助方法(你需要用 nameText
、ageText
等的实际 class 替换 TextField
:
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);
}
以下代码将侦听器添加到多个 SWT 文本元素。唯一的区别是 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());
}
});
...
}
你可以制作一个辅助方法(你需要用 nameText
、ageText
等的实际 class 替换 TextField
:
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);
}