Kotlin 设计模式简介
设计模式(design patterns)是经过验证的典型开发问题解决方案。在 Kotlin 语言中,许多经典模式由于内置特性(如空安全、扩展函数、协程和强大的类型系统)而实现得更加简洁和安全。
本文将介绍三类模式:创建型、结构型和行为型,并附有 Kotlin 的实际示例。您将学习如何在日常开发中使用它们来构建灵活且可维护的架构。
创建型模式(Creational)
1. Singleton(单例)
在 Kotlin 中,单例通过关键字 object 实现。这是一个线程安全的惰性单例,无需额外代码。
object DatabaseConnection { private val url = "jdbc:postgresql://localhost:5432/mydb" private val user = "admin" private val password = "secret"
fun connect(): String { return "Connected to $url as $user" }}
fun main() { println(DatabaseConnection.connect()) // 验证这是同一个对象 val ref1 = DatabaseConnection val ref2 = DatabaseConnection println(ref1 === ref2) // true}优势:无需编写 synchronized 或 volatile —— Kotlin 保证只有一个实例。
2. Factory Method(工厂方法)
允许将对象创建委托给子类。在 Kotlin 中,使用 sealed class 和 companion object 很方便。
sealed class Notification { data class Email(val to: String, val subject: String) : Notification() data class SMS(val phone: String, val message: String) : Notification() data class Push(val deviceId: String, val title: String) : Notification()
companion object Factory { fun createEmail(to: String, subject: String): Notification = Email(to, subject) fun createSMS(phone: String, message: String): Notification = SMS(phone, message) fun createPush(deviceId: String, title: String): Notification = Push(deviceId, title) }}
fun send(notification: Notification) { when (notification) { is Notification.Email -> println("Email to ${notification.to}") is Notification.SMS -> println("SMS to ${notification.phone}") is Notification.Push -> println("Push to ${notification.deviceId}") }}
fun main() { val email = Notification.createEmail("user@example.com", "Hello") send(email)}3. Builder(建造者)
在 Kotlin 中,建造者模式可以用命名参数和默认值替代。但对于需要验证的复杂对象,经典的 Builder 仍然适用。
class Pizza private constructor( val size: String, val cheese: Boolean, val pepperoni: Boolean, val mushrooms: Boolean) { class Builder { private var size: String = "Medium" private var cheese: Boolean = false private var pepperoni: Boolean = false private var mushrooms: Boolean = false
fun size(size: String) = apply { this.size = size } fun cheese() = apply { this.cheese = true } fun pepperoni() = apply { this.pepperoni = true } fun mushrooms() = apply { this.mushrooms = true }
fun build(): Pizza { require(size in listOf("Small", "Medium", "Large")) { "Invalid size" } return Pizza(size, cheese, pepperoni, mushrooms) } }}
fun main() { val pizza = Pizza.Builder() .size("Large") .cheese() .pepperoni() .build() println("Pizza: ${pizza.size}, cheese=${pizza.cheese}, pepperoni=${pizza.pepperoni}")}结构型模式(Structural)
4. Adapter(适配器)
适配器允许不兼容的