所以我有以下场景:
class NowActivity: AppCompatActivity(), NowScreen, NowDelegate by NowDelegateImpl(){
onCreate(...){
presenter.attachView(this)
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以将某些NowScreen方法的实现委托给 NowDelegate 以便我可以在演示者内部执行以下操作:
view.callSomeFunc()
Run Code Online (Sandbox Code Playgroud)
其中 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
...
}
Run Code Online (Sandbox Code Playgroud)
如果委托没有实现两个接口的所有内容,您可以将其设为成员并手动将某些功能子集委托给它。
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() }
}
Run Code Online (Sandbox Code Playgroud)
这两个选项都需要您创建一个默认构造函数,该构造函数创建用于委托的对象并将其传递给主构造函数。
在这里,它被分解为一个包罗万象的示例,该示例不是特定于 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
// ...
}
Run Code Online (Sandbox Code Playgroud)
示例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() }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
480 次 |
| 最近记录: |