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
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
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
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
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.