Singleton Design Pattern in Kotlin

1. Definition

The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. It restricts the instantiation of a class to a single object.

In this tutorial, we will learn how to implement a Singleton Design Pattern using Kotlin programming language.

2. Problem Statement

When designing a system, there might be instances where you want to ensure that a certain class is instantiated only once. This can be due to reasons like controlling access to resources, logging, or any other shared resource.

3. Solution

Use the Singleton pattern to ensure a class controls its instantiation and provides a way to access the instance globally. Kotlin simplifies this with its object declarations.

4. Real-World Use Cases

1. Database connections: Establishing a connection to a database is time-consuming, and you typically want only one connection instance shared in the application.

2. Logger: A logging utility often operates as a singleton, ensuring all parts of an application log messages to a single point of control.

3. Configuration Management: Reading configuration values from sources and providing them to an entire application.

5. Implementation Steps

1. Declare the class with the keyword object.

2. If using a class, make its constructor private.

3. Provide a public method or property to get the instance.

6. Implementation in Kotlin Programming

In Kotlin, we can implement the Singleton Design Pattern in two ways:
1. Using object keyword
2. Using class with a private constructor

Here is the complete source that demonstrates the same:
// Using the 'object' keyword
object SingletonObject {
    fun displayMessage() {
        println("I am a Singleton using the object keyword!")
    }
}
// Using a class
class SingletonClass private constructor() {
    companion object {
        private var INSTANCE: SingletonClass? = null
        fun getInstance(): SingletonClass {
            if (INSTANCE == null) {
                INSTANCE = SingletonClass()
            }
            return INSTANCE!!
        }
    }
    fun displayMessage() {
        println("I am a Singleton using a class!")
    }
}
// Client code
fun main() {
    // Using object declaration
    SingletonObject.displayMessage()
    // Using class
    val singletonInstance = SingletonClass.getInstance()
    singletonInstance.displayMessage()
}

Output:

I am a Singleton using the object keyword!
I am a Singleton using a class!

Explanation:

1. Kotlin provides a straightforward way to declare singletons using the object keyword. This ensures a single instance and handles thread safety.

2. Alternatively, we can use a class with a private constructor and a companion object to control its instantiation and maintain the instance.

3. The client code demonstrates accessing the singleton instance and invoking a method on it.

7. When to use?

Use the Singleton pattern when:

1. You want to eliminate the option of instantiating more than one object.

2. A single point of access to the instance is required.

3. The instance needs to be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Comments