简体   繁体   中英

Use multiple delegates to implement an interface

I need to implement an interface which has about 50 methods (external library, I have no control over that).

Instead of having a single class of 1000 lines, I would like to use several classes to implement a few methods around a single feature each, and have a "main" implementing class that delegates to the feature classes.

Can this be done using delegates in kotlin or do I need to implement each method in the main class?

Sample code without using the delegate system:

class Main: ApiInterface {
  private val f1 = Feature1()
  private val f2 = Feature2()

  override fun m1() = f1.m1()
  override fun m2() = f1.m2()

  override fun m3() = f2.m3()
  override fun m4() = f2.m4()
}

class Feature1 {
  fun m1() { ... }
  fun m2() { ... }
}

class Feature2 {
  fun m3() { ... }
  fun m4() { ... }
}

It is possible very similar to how you did it. The catch is to declare your Feature1 and Feature2 as interfaces and implement them separately:

interface Feature1 {
    fun m1()
    fun m2()
}

interface Feature2 {
    fun m3()
    fun m4()
}

class Feature1Impl() : Feature1 {
    override fun m1() {}

    override fun m2() {}
}


class Feature2Impl : Feature2 {
    override fun m3() {}

    override fun m4() {}
}

The final step is simple composing a new class using kotlins delegation syntax:

class ApiImpl : 
    Feature1 by Feature1Impl(), 
    Feature2 by Feature2Impl(), 
    ApiInterface

or alternatively using constructor parameters:

class ApiImpl(feature1: Feature1, feature2: Feature2) : 
    Feature1 by feature1, 
    Feature2 by feature2, 
    ApiInterface

Note that you need to add the ApiInterface . Since we implemented all required functions, there are not complaints from the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM