替代实现多个接口的类?

问题描述 投票:2回答:1

我们知道,在android studio中,我们可以为对话框或片段创建不同的侦听器,并通过实现它们在上一个活动中使用它们。

但是,随着此过程数量的增加,活动变得过于肿胀,并且可能出现难以辨认的不良代码。

通常这样进行,但是可能有不同的方法。您是否可以针对这种情况建议不同的方法?

下面是一个示例Java代码。我可以为您提供有关Kotlin或Java的建议。这在两个选项中都有用。

public class MainActivity extends BaseControlActivity implements SearchAutoCompleteView.AutoTextControlListener,
    PlateListener, DrawerLayout.DrawerListener, AnimalListener,
    GenderDialog.GenderDialogListener, NotifiyManager.NotifyListener,
    OpenDialog.OpenADialogListener, MainActivityListener, CodeListener {

}
java kotlin interface listener clicklistener
1个回答
0
投票

答案是授权。 Kotlin有很棒的委派工具。

如果侦听器都被接口很好地填充,那么您可以分别实现每个接口,并使每个接口的逻辑保持良好的分区。我在下面包括了一些玩具代码,如果您遇到这种情况,它也具有一些共享状态。

interface MyAPI1 {
    fun doSomething1()
}

interface MyAPI2 {
    fun doSomething2()
}

class MyImplementation1(val state: SomeSharedState) : MyAPI1 {
    override fun doSomething1() {
        TODO("Not yet implemented")
    }
}

class MyImplementation2(val state: SomeSharedState) : MyAPI2 {
    override fun doSomething2() {
        TODO("Not yet implemented")
    }
}

data class SomeSharedState(
    val arbitrary: String
)

/**
 * Here we have the do everything class that combines all interfaces and implementations into one class.
 * It also passes the shared state to each delegated implementation.
 */
class MyDoEverythingImplementation(state: SomeSharedState) :
        MyAPI1 by MyImplementation1(state),
        MyAPI2 by MyImplementation2(state)
© www.soinside.com 2019 - 2024. All rights reserved.