Singleton Pattern in Kotlin - Design Patterns for Dummies

In this article, you will learn about the basic concepts of Design Patterns, their advantages, and types. You will also see an example of the Singleton Design pattern in Kotlin for Android.

Design Patterns

Design Patterns are used to solve commonly occurring problems in Software Development. Basically, these not only provide the solutions, but they also show you the way to write readable and reusable code. This helps you as a developer to avoid reinventing the wheel and use the battle-tested code methods and approaches for your projects.




Types of Design Patterns

There have been many designs patterns created by developers till now. These are divided in 3 major groups namely Creational, Structural and Behavioral patterns. Now, let’s explore each below.

Creational Patterns

An illustration of a Factory depicting Factory pattern An illustration of a Factory depicting Factory pattern

Creational patterns are concerned with the creation and instantiation of some complex objects. For example, you have a class A and you want to use a single and same instance of it in 5 different classes, a design pattern will be helpful here. Or maybe you have a class which depends on other dependency classes, then creating that main object is going to be a bit complex. The Creational Design patterns provide you with the ability to deal with such kinds of scenarios.

Some of the Creational Patterns that developers most of the time uses in Android Application Development are Singleton pattern, Factory pattern, Builder pattern, Dependency Injection.

Structural Patterns

An illustration of a bricks depicting Composite pattern An illustration of a bricks depicting Composite pattern

The Structural Design patterns help you to with your large complex structures which are made of the classes and objects. It focuses on how several classes are related to each other, which inherits whom, and how they all are composed or organized to form a large structure for your app. Think of a RecyclerView without using an Adapter and how they can work to show the data for your app.

Some common structural patterns are Adapter, Facade, Decorator, and Composite patterns.

Behavioral Patterns

An illustration of a TV set depicting Observer pattern An illustration of a TV set depicting Observer pattern

Behavioral Design patterns are all about the responsibilities and behavior of classes and objects, from the relationship between objects to how objects communicate with each other.

Some behavioral patterns Observe, Common, Strategy and State patterns.

Now, you will explore about the Singleton pattern and how it can be implemented in Kotlin for Android. The other parts of this series will focus on other design patterns.



Singleton Design Pattern

An illustration of a Singelton pattern - Image: https://refactoring.guru/design-patterns/singleton An illustration of a Singelton pattern - Image: https://refactoring.guru/design-patterns/singleton

The most widely used and most helpful design pattern is the Singleton Design pattern or Singleton approach. Singleton is just like the static of C++ and Java which means a single and same instance of a class will be used by the whole program.

You need singleton in scenarios where you only need a single object or instance of one class in your whole application. For example, you have customer’s data like customer ID, name, list of items he/she they purchased and the total bill. Your task is to keep this data handy for your app to access anywhere. The data can be updated, modified or deleted anywhere. So, you must be careful to keep only a single instance of this data. Otherwise, app could lead to data duplication, causing the inconsistencies and bugs in your app. This is where singleton patterns can ensure that the only one and same instance is being used wherever you need that data.

In Kotlin, the object keyword is used to define a singleton.

object CustomerData {
    var customerId = “123”
    var name = “John”
    var totalBill = 284.34
    var purchasedItems: List<Item> = arrayListOf()

    fun addItem(item: Item) {
        purchasedItems.add(item)
        totalBill = calculateBill()
    }

    fun calculateBill(): Float {
        // Some calculations
        return newBill;
    }
}

So this is how the singleton will look like. Your singleton is just like a class, only it should start with the keyword object instead of the class, Now, Kotlin will not allow you to create any other instances of this CustomerData at all. There will be only one instance throughout whole app.

And you can call the functions defined inside Singleton by using . after the name of a singleton as:

CustomerData.addItem(someItem)

Hope this clears your concept about design patterns and especially about the Singleton pattern in Kotlin. At the end, please Subscribe to my newsletter #Time with Wajahat to learn learn about the life experiences, lessons, career advices, technology & programming tips manually handcrafted and curated by Wajahat Karim.


If you liked this article, you can read my new articles below:


profile card
Wajahat Karim
🌍 Making the world a better place, one app at a time.
🔥 Google Developer Expert (GDE) in Android . 📱 Professional Android Developer with ~10 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.
Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan