【问题标题】:Android Kotlin Mvp Class delegationAndroid Kotlin Mvp 类委托
【发布时间】:2016-10-06 10:14:58
【问题描述】:

所以我有以下场景:

  class NowActivity: AppCompatActivity(), NowScreen, NowDelegate by NowDelegateImpl(){

  onCreate(...){
       presenter.attachView(this)
  }

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

view.callSomeFunc()

其中 callSomeFund() 在 NowDelegate 中实现。

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

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

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

    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() }
    }
    

    【讨论】:

    • 没有构造函数的活动怎么办......你能做到吗?
    • 什么意思它没有构造函数,谁来构造activity?
    • @user3806331 好的,通过添加调用另一个构造函数的默认构造函数来修复我的答案
    猜你喜欢
    • 2018-05-07
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多