Kotlin 对象与伴生对象 #

一、对象声明 #

1.1 单例模式 #

使用 object 关键字声明单例:

kotlin
object Database {
    private val connections = mutableListOf<Connection>()
    
    fun connect(): Connection {
        val connection = Connection()
        connections.add(connection)
        return connection
    }
    
    fun disconnectAll() {
        connections.clear()
    }
}

Database.connect()
Database.disconnectAll()

1.2 对象初始化 #

kotlin
object Singleton {
    init {
        println("Singleton initialized")
    }
    
    var count = 0
    
    fun increment() = count++
}

Singleton.increment()
Singleton.increment()
println(Singleton.count)  // 2

1.3 对象作为类型 #

kotlin
object Printer {
    fun print(message: String) {
        println(message)
    }
}

fun usePrinter(printer: Printer) {
    printer.print("Hello")
}

usePrinter(Printer)

二、伴生对象 #

2.1 定义伴生对象 #

kotlin
class MyClass {
    companion object {
        const val CONSTANT = "Constant"
        
        fun staticMethod() {
            println("Static method")
        }
    }
}

MyClass.CONSTANT
MyClass.staticMethod()

2.2 命名伴生对象 #

kotlin
class MyClass {
    companion object Factory {
        fun create(): MyClass = MyClass()
    }
}

MyClass.create()
MyClass.Factory.create()

2.3 实现接口 #

kotlin
interface Factory<T> {
    fun create(): T
}

class User(val name: String) {
    companion object : Factory<User> {
        override fun create(): User = User("Default")
    }
}

val user = User.create()

2.4 扩展伴生对象 #

kotlin
class MyClass {
    companion object
}

fun MyClass.Companion.extension() {
    println("Extension function")
}

MyClass.extension()

三、对象表达式 #

3.1 匿名对象 #

kotlin
interface ClickListener {
    fun onClick()
}

val listener = object : ClickListener {
    override fun onClick() {
        println("Clicked")
    }
}

listener.onClick()

3.2 继承类 #

kotlin
open class Handler {
    open fun handle() {
        println("Handling")
    }
}

val handler = object : Handler() {
    override fun handle() {
        println("Custom handling")
    }
}

3.3 访问局部变量 #

kotlin
fun countClicks(): Int {
    var clicks = 0
    
    val listener = object : ClickListener {
        override fun onClick() {
            clicks++
        }
    }
    
    listener.onClick()
    listener.onClick()
    
    return clicks
}

四、单例模式实现 #

4.1 object 声明 #

kotlin
object Database {
    fun query(sql: String): List<Any> {
        return emptyList()
    }
}

4.2 伴生对象 + lazy #

kotlin
class Singleton private constructor() {
    companion object {
        val instance: Singleton by lazy { Singleton() }
    }
}

val singleton = Singleton.instance

4.3 双重检查锁定 #

kotlin
class Singleton private constructor() {
    companion object {
        @Volatile
        private var instance: Singleton? = null
        
        fun getInstance(): Singleton {
            return instance ?: synchronized(this) {
                instance ?: Singleton().also { instance = it }
            }
        }
    }
}

五、实战示例 #

5.1 配置管理 #

kotlin
object AppConfig {
    var apiUrl: String = "https://api.example.com"
    var timeout: Long = 30000
    var debug: Boolean = false
    
    fun load(config: Map<String, Any>) {
        apiUrl = config["apiUrl"] as? String ?: apiUrl
        timeout = config["timeout"] as? Long ?: timeout
        debug = config["debug"] as? Boolean ?: debug
    }
}

AppConfig.load(mapOf(
    "apiUrl" to "https://prod.example.com",
    "debug" to true
))

5.2 工厂模式 #

kotlin
interface Shape {
    fun draw()
}

class Circle : Shape {
    override fun draw() = println("Drawing Circle")
}

class Square : Shape {
    override fun draw() = println("Drawing Square")
}

object ShapeFactory {
    fun create(type: String): Shape {
        return when (type.lowercase()) {
            "circle" -> Circle()
            "square" -> Square()
            else -> throw IllegalArgumentException("Unknown shape: $type")
        }
    }
}

val circle = ShapeFactory.create("circle")
circle.draw()

5.3 日志工具 #

kotlin
object Logger {
    private var level = LogLevel.INFO
    
    enum class LogLevel {
        DEBUG, INFO, WARN, ERROR
    }
    
    fun setLevel(level: LogLevel) {
        this.level = level
    }
    
    fun debug(message: String) {
        if (level <= LogLevel.DEBUG) println("[DEBUG] $message")
    }
    
    fun info(message: String) {
        if (level <= LogLevel.INFO) println("[INFO] $message")
    }
    
    fun warn(message: String) {
        if (level <= LogLevel.WARN) println("[WARN] $message")
    }
    
    fun error(message: String) {
        if (level <= LogLevel.ERROR) println("[ERROR] $message")
    }
}

Logger.info("Application started")
Logger.error("Something went wrong")

5.4 回调实现 #

kotlin
interface Callback {
    fun onSuccess(result: String)
    fun onError(error: String)
}

fun fetchData(callback: Callback) {
    try {
        Thread.sleep(100)
        callback.onSuccess("Data loaded")
    } catch (e: Exception) {
        callback.onError(e.message ?: "Unknown error")
    }
}

fetchData(object : Callback {
    override fun onSuccess(result: String) {
        println("Success: $result")
    }
    
    override fun onError(error: String) {
        println("Error: $error")
    }
})

六、object vs companion object #

6.1 区别 #

特性 object companion object
位置 顶层 类内部
访问方式 直接通过名称 通过类名
数量 多个 每个类一个
继承 可以继承 可以继承

6.2 选择建议 #

kotlin
// 使用 object:全局单例
object Database { }

// 使用 companion object:与类关联的静态成员
class User {
    companion object {
        fun create() = User()
    }
}

七、最佳实践 #

7.1 单例使用 object #

kotlin
// 推荐
object Singleton {
    fun doSomething() { }
}

// 不推荐
class Singleton private constructor() {
    companion object {
        val instance = Singleton()
    }
}

7.2 常量使用 companion object #

kotlin
class Constants {
    companion object {
        const val MAX_SIZE = 100
        const val DEFAULT_TIMEOUT = 30000L
    }
}

7.3 工厂方法使用 companion object #

kotlin
class User private constructor(val name: String) {
    companion object {
        fun create(name: String): User {
            return User(name.trim())
        }
        
        fun createGuest(): User {
            return User("Guest")
        }
    }
}

八、总结 #

对象要点:

类型 用途
object 单例、工具类
companion object 静态成员、工厂方法
object expression 匿名实现

下一步,让我们学习 集合概述

最后更新:2026-03-27