Android多态:反模式?

jos*_*ard 8 java polymorphism android

我正在阅读O'Reilly的"Programming 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

后来由于缺乏可扩展性封装而将其称为反模式:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有看到两者之间的功能差异,除了第二个更具可读性.两者都采用TextView,并实现一个处理函数来覆盖.难道第二个不会像这样容易扩展吗?

public class AnotherModel extends MyModel {
    @Override
    void handleTextChange(Editable s) {
         // another implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

rua*_*akh 2

由于缺乏可扩展性而导致的反模式

在可扩展性方面,它们的相似之处在于这两种方法都允许子类TextChangeListener通过重写轻松修改现有的handleTextChange;但它们的不同之处在于,只有方法 #2 还可以让子类轻松添加新的 TextChangeListener类,而无需修改现有的(继承的)类。

即使超类使用方法#1,子类仍然可以TextChangeListener使用方法#2 添加新的;但如果我们讨论一般使用的模式,那么一致使用方法 #2 将比一致使用方法 #1 提供更多的可扩展性。