简体   繁体   English

在android / java中传递信息的最佳做法

[英]Best practices for passing information in android/java

Hi I'm writing an app in android and was wondering about best practices and potential advantages and disadvantages of each the methods presented below if you want to call a method defined in Class A from Class B or pass information from class A to B 嗨,我正在用android编写应用程序,想知道下面介绍的每种方法的最佳实践以及潜在的优缺点,如果您要从B类调用A类中定义的方法,或者将信息从A类传递给B

Method1: Passing Method A as argument. 方法1:将方法A作为参数传递。

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

Method2: Defining a interface. 方法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(){
        ...
    }
}

In the android docs I read that the preferred way for passing information from a Fragment to an Activity is the second method. 在android文档中,我读到了将信息从Fragment传递到Activity的首选方法是第二种方法。 But was wondering why this is the case? 但是想知道为什么会这样吗?

If I'm understanding your question correctly, this sounds more like a question about why/when to use interfaces in OOP. 如果我正确理解了您的问题,这听起来更像是关于为什么/何时在OOP中使用接口的问题。

The best example would be when we add another class, C. If class C implements A.Helper as well, then you can pass C into A no problem, using the second method. 最好的例子是当我们添加另一个类C时。如果类C也实现了A.Helper,则可以使用第二种方法将C毫无问题地传递给A。 If you use the first method, C can not be passed into A, because it is expecting an object of type B. 如果使用第一种方法,则C不能传递给A,因为它需要一个B类型的对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM