Skip to Content
Kotlin📘 Ngôn ngữ KotlinObject Declaration và Singleton

Object Declaration và Singleton trong Kotlin

1. Giới thiệu

Object declaration là cách đơn giản nhất để tạo singleton trong Kotlin.

2. Object Declaration

object DatabaseConnection { private var isConnected = false fun connect() { isConnected = true println("Connected to database") } fun disconnect() { isConnected = false println("Disconnected") } fun status() = if (isConnected) "Connected" else "Disconnected" } fun main() { DatabaseConnection.connect() println(DatabaseConnection.status()) }

3. Object với Properties

object Config { const val API_URL = "https://api.example.com" const val TIMEOUT = 30000 var debug = false val version: String get() = "1.0.0" } fun main() { println(Config.API_URL) Config.debug = true }

4. Object implement Interface

interface Logger { fun log(message: String) } object ConsoleLogger : Logger { override fun log(message: String) { println("[LOG] $message") } } fun main() { ConsoleLogger.log("Hello!") }

5. Object kế thừa Class

open class Animal(val name: String) { open fun speak() = println("$name speaks") } object Parrot : Animal("Polly") { override fun speak() = println("$name says: Hello!") } fun main() { Parrot.speak() // Polly says: Hello! }

6. Object Expression (Anonymous Object)

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

7. Object Expression với multiple interfaces

interface Drawable { fun draw() } interface Clickable { fun click() } fun main() { val button = object : Drawable, Clickable { override fun draw() = println("Drawing button") override fun click() = println("Button clicked") } button.draw() button.click() }

8. Object Expression trong function

fun createCounter() = object { var count = 0 fun increment() { count++ println("Count: $count") } } fun main() { val counter = createCounter() counter.increment() // Count: 1 counter.increment() // Count: 2 }

9. So sánh Declaration vs Expression

// Object Declaration - singleton, có tên object Singleton { fun doSomething() {} } // Object Expression - không phải singleton, có thể anonymous val myObject = object { val x = 10 val y = 20 }

10. Singleton Pattern

object AppState { private val observers = mutableListOf<() -> Unit>() private var _count = 0 val count: Int get() = _count fun increment() { _count++ notifyObservers() } fun addObserver(observer: () -> Unit) { observers.add(observer) } private fun notifyObservers() { observers.forEach { it() } } } fun main() { AppState.addObserver { println("Count changed: ${AppState.count}") } AppState.increment() // Count changed: 1 }

📝 Tóm tắt

  • object Name tạo singleton
  • Thread-safe và lazy initialization
  • Có thể implement interfaces, extend classes
  • Object expression cho anonymous objects
  • Thay thế anonymous inner class trong Java
  • Không có constructor
Last updated on