O'Reillyの「ProgrammingAndroid」の本を読んでいて、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.
}
}
2つ目がはるかに読みやすいことを除けば、2つの機能の違いはわかりません。どちらもTextViewを受け取り、オーバーライドするハンドラー関数を実装します。2つ目は、このようなもので拡張するのと同じくらい簡単ではないでしょうか?
public class AnotherModel extends MyModel {
@Override
void handleTextChange(Editable s) {
// another implementation
}
}