Android Kotlin Mvp类代表团

所以我有以下情况:

class NowActivity: AppCompatActivity(), NowScreen, NowDelegate by NowDelegateImpl(){ onCreate(...){ presenter.attachView(this) } 

有什么办法可以将一些NowScreen方法的实现委托给NowDelegate,所以我可以在演示者中执行以下操作:

 view.callSomeFunc() 

其中callSomeFund()在NowDelegate实现。

有没有办法完成这样的事情? 问题是我正在使用MVP,它将视图添加到演示者。 但是一些视图的实现在几个活动中重复,所以我想把它委托给另一个类。

如果它实现了两个接口,则可以将这两个接口委托给同一个对象。 为此,只需将该对象设置为构造函数参数,例如:

 class NowActivity(delegate: NowDelegateImpl): AppCompatActivity(), NowScreen by delegate, NowDelegate by delegate { constructor (): this(NowDelegateImpl()) {} // need this default constructor for Android to call ... } 

如果委托没有实现两个接口的一切,你可以使它成为一个成员,并手动委托一些功能的子集。

 class NowActivity(private val delegate: NowDelegateImpl): AppCompatActivity(), NowScreen, NowDelegate by delegate { constructor (): this(NowDelegateImpl()) {} // need this default constructor for Android to call override fun callSomeFund() { delegate.callSomeFund() } } 

这两个选项都需要您创建一个默认的构造函数来创建用于委派的对象,并将其传递给主构造函数。

在这里,它被分解为一个全面的示例,这不是特定于Android的情况,以防其他人想要看到正在发生的事情。

示例1,将所有接口委托给同一个对象:

 interface CommonStuff { fun foo1() fun foo2() } interface LessCommonStuff { fun bar() } class CommonDelegate1: CommonStuff, LessCommonStuff { override fun foo1() {} override fun foo2() {} override fun bar() {} } class Activity1(delegate: CommonDelegate1): LessCommonStuff by delegate, CommonStuff by delegate { constructor (): this(CommonDelegate1()) {} // need this default constructor // ... } 

示例2,使用成员手动委派一些接口:

 interface CommonStuff { fun foo1() fun foo2() } interface LessCommonStuff { fun bar() } class CommonDelegate2: CommonStuff { override fun foo1() {} override fun foo2() {} fun barLikeThing() {} } class Activity2(private val delegate: CommonDelegate2): LessCommonStuff, CommonStuff by delegate { constructor (): this(CommonDelegate2()) {} // need this default constructor override fun bar() { delegate.barLikeThing() } }