Design Patterns: Singleton – with Kotlin Examples

Till now all the patterns that we talked about are creational design patterns, and as we said before creational design patterns abstract the instantiation process and help to make the system independent of how its objects are created, composed, and represented.

In this post, I will talk about the Singleton pattern. Which is the last pattern in the creational patterns category as mentioned in the Gang of four book. This post probably will be the shortest in the series.

The Singleton pattern as defined in the book

Ensure a class only has one instance, and provide a global point of access to it.

The previous statement may sound very simple but let’s dig into it.

Some classes should have exactly one instance to be used throughout the application, hence comes the Singleton pattern to assure thatIn Java, we use the keyword new each time we want to instantiate an object of a class. So new give us a new instance of the class. But in Singleton pattern, we want only a single instance of the class and by using new keyword we will violate the first part of the Singleton pattern definition. So how we can assure that there is only one object that is instantiated for a given class?

A global variable can provide a global point of access to the class but using a global variable has many downsides such as that the global variable might be created when the application begins and assuming that object is using your resources intensively but your application never ends up using it, also using global variable don’t always keep you from instantiating multiple objects.

So the solution is to make the class itself responsible for ensuring that there is only one instance of itself throughout the entire application, and also provide a way to access that instance. In java to achieve that, the constructor of the class should be private. Yes I meant what I just said, the constructor of the class should be private so no other class can instantiate the class. So how we can get an instance of that class if we cannot access its constructor?

We create a static function in the class that responsible for keeping track of its unique instance, one and only instance then the static function can be called using the class name anywhere in the application. That applies not just in Java,  but anywhere you want to use the Singleton pattern.

To be more concrete let’s look at the structure of the Singleton pattern.

As the above UML shows that the Singleton defines getInstance() function -which is a class operation- that lets the clients access its unique instance. The UML also showed that the Singleton constructor is private. Also, the Singleton may be responsible for creating its unique instance.

To create Singleton in java you may use something like the following:

public class Singleton {
    private static Singleton uniqueInstance;
    
    private Singleton() {

    }

    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }

        return uniqueInstance;
    }
}

 

There are many implementations of the Singleton pattern. The above one is called lazy initialization.

The equivalent in Kotlin is simply:

object Singleton

 

Yes, as simple as that, that’s how to create a Singleton class in Kotlin.
Here is a working example of using Singleton in Kotlin.

object Singleton {
    init {
        println("Singleton initialized")
    }

    var message = "Kotlin rock"

    fun showMessage() {
        println(message)
    }
}

class Test {
    init {
        Singleton.showMessage()
    }
}

fun main() {
    Singleton.showMessage()
    Singleton.message = "Kotlin is cool"

    val test = Test()
}

 

The output will be:

Singleton initialized
Kotlin rock
Kotlin is cool

 

As you can see that the Singleton object initialized only once, and now we have a single instance of the Singleton object.

Singleton can be used to implement many patterns, such as Abstract FactoryBuilder, and Prototype.

So as a recap the Singleton pattern is simply ensuring that a class has only one unique instance and provides an access point to that instance.

And that’s it. That is the Singleton pattern. And as always you can refer to the GoF book for more.

So that’s all I have for this post and I always appreciate feedback and If you have any question please put your questions in the comments.

Till the next pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *