Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Singleton

Singleton is a class which has only one instance (object).

Singleton is one of the most important Software Design Pattern. A Software Design Pattern is a guideline or solution to a general problem in Software Design. There are several more patterns, you can learn more about them here.

Where exactly do we need just a single instance of a class? When developing a software, we may need to use several services such as a DatabaseService. DatabaseService provides connection to a database and exposes functions to read and write data. If we instantiate such services multiple times, we may end up opening several connections to the database which might be computationally expensive. It can also be memory expensive if multiple instances are created. We will learn more about this pattern in later modules while developing complex apps. For now, let’s consider simple usecases of Singletons.

A Singleton can be created to group related classes, functions or data into a single entity. Then, it can be used globally across multiple files, withouting creating new instance.

We can create a singleton using the object keyword :

 object /* name */ {
		// members
}
 

Examples

Utilities

We can create singleton to group related utility functions into a single entity. Suppose we define multiple functions related to calendar :

  • isLeapYear(year: Int): Boolean
  • getNoOfDaysInMonth(month: Int, year: Int): Int
  • getNoOfDaysBetween(start: Date, end: Date): Int

Instead of defining them directly in a file, we can define them in a singleton called CalendarUtils :

 object CalendarUtils {

    fun isLeapYear(year: Int): Boolean { TODO() }

    fun getNoOfDaysInMonth(month: Int, year: Int): Int { TODO() }

    fun getNoOfDaysBetween(start: Date, end: Date): Int { TODO() }
}
 

We can directly access this functions using the singleton name :

 object CalendarUtils {

    fun isLeapYear(year: Int): Boolean { TODO() }

    fun getNoOfDaysInMonth(month: Int, year: Int): Int { TODO() }

    fun getNoOfDaysBetween(start: Date, end: Date): Int { TODO() }
}

fun main() {
		val is2020ALeapYear = CalendarUtils.isLeapYear(2020)
		val noOfDaysInFeb2023 = CalendarUtils.getNoOfDaysInMonth(2, 2023)
}
 

Constants

We can create singleton to group multiple constants. Constant is a variable with fixed value used all across an application. For example, in a game we may have constants like

  • maximum lifelines,
  • total number of levels,
  • maximum number of players etc.

We can define them in a singleton called Constants :

 object Constants {
    const val MAX_LIFELINES = 20
    const val TOTAL_LEVELS = 100
    const val MAX_PLAYERS = 6
}
 

We can access them directly as :

 if (level == Constants.TOTAL_LEVELS) {
    println("Congratulations, you have completed the game!")
}
 

Note :

  • Singletons don’t have constructors. They are constructed as soon as the program runs and reside in memory till the end.
  • Like normal classes, singetons can also inherit from open classes.
  • Singletons can’t be declared as open i.e. they can’t be inherited.