我正在阅读 O'Reilly 的“Programming Android”一书,并试图从第 99 页开始围绕“Overrides and Callbacks”部分展开思考。他们将此作为良好代码的示例:
public class MyModel {
public MyModel(TextView textBox) {
textBox.addTextChangedListener(
new TextWatcher() {
public void afterTextChanged(Editable s) {
handleTextChange(s);
}
// ...
}
void handleTextChange(Editable s) {
// do something with s, the changed text.
}
}
由于缺乏可扩展性封装,后来将其称为反模式:
public class MyModel implements TextWatcher {
public MyModel(TextView textBox) {
textBox.addTextChangedListener(this);
}
public void afterTextChanged(Editable s) {
handleTextChange(s);
}
// ...
void handleTextChange(Editable s) {
// do something with s, the changed text.
}
}
除了第二个更具可读性之外,我没有看到两者之间的功能差异。两者都采用 TextView,并实现一个处理函数来覆盖。用这样的东西扩展第二个不是很容易吗?
public class AnotherModel extends MyModel {
@Override
void handleTextChange(Editable s) {
// another implementation
}
}