Kotlin将多个第三方接口封装为一个

uqjltbpv  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(221)

第三方库库:

  • 无法修改
  • 服务型图书馆
interface I3rdParty1 {
  fun fun1(): Int?
  fun fun2()
  //...
  fun funA()
  fun funB()
  //...
}

interface I3rdParty2 {
  fun fun1(): Int?
  fun fun2()
  //...
  fun funX()
  fun funY()
  //...
}

class Service() {
  fun getService1(): I3rdParty1
  fun getService2(): I3rdParty2
}

备注:

  • 两者都有相同的函数签名集。
  • 没有同名但签名不同的函数。
  • 只能使用其中一项服务,而不能同时使用两项服务。
  • 在两个接口上大约有10个公共接口和5个唯一接口。

在我的代码中,目标是封装两个服务并将它们合并成一个或其他东西,而不添加样板代码。

interface MyService extends I3rdParty1, I3rParty2 {
  // Can I not write all 15 common ones and 2x5 uniques ones here?
}

class MyCode() : MyService {
  var service1: I3rdParty1? = null
  var service2: I3rdParty2? = null
  
  fun detectService() {
    service1 = Service().getService1()
    service2 = Service().getService2()
  }

  // Is there a way to simplify this?

  override fun1(): Int? {
    return if (service1 != null)
     service1.fun1()
    else if (service2 != null)
     service2.fun1()
    else null
  }

  override fun2() {
    if (service1 != null)
     service1.fun2()
    else if (service2 != null)
     service2.fun2()
  }

}
fd3cxomn

fd3cxomn1#

您可以使用Delegation模式。

interface I3rdParty1 {
    fun fun1(): Int?
    fun fun2()
    //...
    fun funA()
    fun funB()
    //...
}

interface I3rdParty2 {
    fun fun1(): Int?
    fun fun2()
    //...
    fun funX()
    fun funY()
    //...
}

class Service() {
    fun getService1(): I3rdParty1
    fun getService2(): I3rdParty2
}

interface MyService : I3rdParty1, I3rdParty2

class MyCode(private val service: Service) : MyService {
    private val service1: I3rdParty1? = service.getService1()
    private val service2: I3rdParty2? = service.getService2()

    override fun fun1(): Int? = service1?.fun1() ?: service2?.fun1()
    override fun fun2() = service1?.fun2() ?: service2?.fun2()
    override fun funA() = service1?.funA() ?: service2?.funA()
    override fun funB() = service1?.funB() ?: service2?.funB()
    override fun funX() = service1?.funX() ?: service2?.funX()
    override fun funY() = service1?.funY() ?: service2?.funY()
}

?:的解释:

service1?.fun1() ?: service2?.fun1()

相当于

if (service1 != null) {
    service1.fun1()
} else {
    service2?.fun1()
}

相关问题