Kotlin设计模式示例:从A到Z
设计模式(design patterns)是经过验证的典型开发问题解决方案。在Kotlin中,凭借其简洁的语法和强大的特性(data class、object、扩展函数、协程),许多经典模式的实现比Java更简单、更优雅。本文将深入解析Kotlin中从创建型到行为型的关键模式,并附有实际代码示例。
1. 创建型模式(Creational)
这些模式管理对象的创建过程,使系统独立于对象的创建方式。
1.1. 单例模式(Singleton)
确保一个类只有一个实例。在Kotlin中,使用关键字object实现。
object DatabaseConnection { val connectionString: String = "jdbc:postgresql://localhost:5432/mydb"
fun connect() { println("Connecting to $connectionString") }}
fun main() { DatabaseConnection.connect() println(DatabaseConnection.connectionString)}使用场景:配置管理器、线程池、缓存。
1.2. 工厂方法模式(Factory Method)
定义创建对象的接口,但允许子类更改所创建对象的类型。
// 抽象产品interface Notification { fun send(message: String)}
// 具体产品class EmailNotification : Notification { override fun send(message: String) = println("Email: $message")}
class SMSNotification : Notification { override fun send(message: String) = println("SMS: $message")}
// 工厂abstract class NotificationFactory { abstract fun createNotification(): Notification
fun notifyUser(message: String) { val notification = createNotification() notification.send(message) }}
class EmailFactory : NotificationFactory() { override fun createNotification(): Notification = EmailNotification()}
class SMSFactory : NotificationFactory() { override fun createNotification(): Notification = SMSNotification()}
fun main() { val factory: NotificationFactory = EmailFactory() factory.notifyUser("Hello from Kotlin!")}使用场景:当预先不知道要创建的对象类型时。
1.3. 建造者模式(Builder)
允许逐步创建复杂对象。在Kotlin中,通过apply和命名参数可以很好地实现。
data class Pizza( val size: String, val cheese: Boolean = false, val pepperoni: Boolean = false, val mushrooms: Boolean = false) { // 内置Builder class Builder(private val size: String) { private var cheese: Boolean = false private var pepperoni: Boolean = false private var mushrooms: Boolean = false
fun cheese(value: Boolean) = apply { cheese = value } fun pepperoni(value: Boolean) = apply { pepperoni = value } fun mushrooms(value: Boolean) = apply { mushrooms = value }
fun build() = Pizza(size, cheese, pepperoni, mushrooms) }}
fun main() { val pizza = Pizza.Builder("Large") .cheese(true) .pepperoni(true) .build() println(pizza)}使用场景:当有大量可选参数时。
2. 结构型模式(Structural)
这些模式定义了类和对象的构建方式,以形成更大的结构。
2.1. 适配器模式(Adapter)
允许接口不兼容的对象协同工作。在Kotlin中,常通过扩展函数实现。
// 旧接口interface OldLogger { fun logMessage(msg: String)}
// 新接口interface NewLogger { fun log(level: Stri