【问题标题】:Best practices for passing information in android/java在 android/java 中传递信息的最佳实践
【发布时间】:2018-08-02 15:54:22
【问题描述】:

您好,我正在用 android 编写一个应用程序,如果您想从 Class B 调用 Class A 中定义的方法或将信息从 Class A 传递给乙

方法 1:将方法 A 作为参数传递。

class A {
    B object;
    A(B object) {
        this.object = object;
    }
    void someMethod() {
        object.someOtherMethod();
    }
}
class B {
    void someOtherMethod(){
        ...
    }
}

方法2:定义接口。

class A {
    Helper helper;
    A(Helper helper) {
        this.helper= helper;
    }
    void someMethod() {
        helper.someOtherMethod();
    }
    interface Helper {
        void someOtherMethod();
    }
}
class B implements A.Helper {
    @Override
    void someOtherMethod(){
        ...
    }
}

在 android 文档中,我读到将信息从 Fragment 传递到 Activity 的首选方法是第二种方法。但想知道为什么会这样?

【问题讨论】:

    标签: java android calling-convention


    【解决方案1】:

    如果我正确理解您的问题,这听起来更像是一个关于为什么/何时在 OOP 中使用接口的问题。

    最好的例子是当我们添加另一个类 C 时。如果类 C 也实现了 A.Helper,那么您可以使用第二种方法将 C 传递给 A 没有问题。如果使用第一种方法,C 不能传递给 A,因为它需要 B 类型的对象。

    进一步阅读:https://softwareengineering.stackexchange.com/questions/145437/why-use-an-interface-when-the-class-can-directly-implement-the-functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 2023-03-22
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多