我正在阅读 O'Reilly 的“Android 编程”一书,我正在努力研究从第 99 页开始的“覆盖和回调”部分。他们将此作为优秀代码的示例:
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
}
}
最佳答案
an anti-pattern due to lack of extensibility
在可扩展性方面,它们的相似之处在于这两种方法都允许子类通过覆盖 handleTextChange
轻松修改现有的 TextChangeListener
;但它们的不同之处在于,唯一的方法 #2 还使子类可以轻松添加新 TextChangeListener
,而无需修改现有(继承的)。
即使父类(super class)使用方法 #1,子类仍然可以使用方法 #2 添加新的 TextChangeListener
;但是如果我们谈论的是一般使用的模式,那么一致使用方法 #2 将比一致使用方法 #1 提供更多的可扩展性。
关于java - 安卓多态: Anti-Pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13725741/