In object oriented programming, there is a common situation when you want a class to have only one instance. In Java, we usually implement using the Singleton Design Pattern: define a class with a private constructor and a static field holding the only existing instance of that class. This tutorial shows you a way to implement Singleton with Kotlin Object Declaration.
>>> Refer to: JavaSampleApproach.com
I. Technology
– Java 1.8
– Kotlin 1.1.2
II. Overview
Kotlin provides object declaration feature with keyword object
.
We use object
keyword in several cases, but they all have the same core idea:
– defines a class, and at the same time
– creates an instance (an object) of that class
Like a class, an object declaration can contain declarations of properties, methods…
1 2 3 4 5 6 7 8 9 10 11 12 |
object Singleton { init { ... } var a: Int = ... fun doWork() { ... } } |
But constructors are not allowed. Object declarations are created immediately at the point of definition, not through constructor. So defining a constructor in this case doesn’t make sense.
Object declarations can also inherit from class
and interface
.
You can call methods and access properties simply:
1 2 |
calculate(Singleton.a) Singleton.doWork() |
III. Practice
1. Object Declaration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.kotlination.singleton object Singleton { var message: String = "default Message" init { println("Initializing object: $this") } fun showSingleMessage() { println("Message: " + message) } fun setSingleMessage(message: String) { this.message = message } } |
2. Run & Check Result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.kotlination.singleton fun main(args: Array<String>) { println("--- Singleton ---") println(Singleton.message) Singleton.showSingleMessage() Singleton.setSingleMessage("Hello Kolination!") println("--- singleton1 ---") val singleton1 = Singleton singleton1.showSingleMessage() Singleton.setSingleMessage("Hello Kolineer!") println("--- singleton2 ---") val singleton2 = Singleton singleton2.showSingleMessage() } |
Result:
1 2 3 4 5 6 7 8 |
--- Singleton --- Initializing object: com.kotlination.singleton.Singleton@232204a1 default Message Message: default Message --- singleton1 --- Message: Hello Kolination! --- singleton2 --- Message: Hello Kolineer! |