在 Kotlin 中,适配器模式可以通过创建一个新类来实现,该类将不兼容的接口转换为客户端期望的接口。以下是一个简单的 Kotlin 适配器模式的实现示例:
interface Target { fun request() }
class Adaptee { fun specificRequest() { println("Called specificRequest()") } }
class Adapter : Target { private val adaptee: Adaptee constructor(adaptee: Adaptee) { this.adaptee = adaptee } override fun request() { adaptee.specificRequest() } }
fun main() { val adaptee = Adaptee() val target = Adapter(adaptee) target.request() }
当运行此代码时,将看到以下输出:
Called specificRequest()
这就是如何在 Kotlin 中实现适配器模式。适配器模式允许您在不修改现有类的情况下,将不兼容的接口转换为客户端期望的接口。