java - 安卓多态: Anti-Pattern?

标签 java android polymorphism

我正在阅读 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/

相关文章:

java - 如何在 Spring JPA 应用程序中集成 paypal Rest api。错误代码 400

java - TestNG:使用 Dataprovider 迭代数组

java - 有没有人用 couchbase-lite-android 1.02 实现了 robolectric 2.3?

android - 无法启动模拟器。原因 : Emulator exited before boot en React Native when react-native run-android

c++ - 基类指针只得到一个派生类变量值而不是基类变量值为什么?

c++ - 需要关于多重继承和可选函数覆盖 C++ 的建议

delphi - 隐藏成员变量和/或过程时编译器不会发出警告

java - Firebase 可扩展性 - 查询 DB 与自定义对象 ArrayList?

小型 VPS 上的 Java Servlet 容器

Android studio appengine 端点不包含构建器