Advanced Object-Oriented Programming in Kotlin

May 22 2024 · Kotlin 1.9, Android 14, Kotlin Playground

Lesson 02: Design Patterns

Implementing Singleton Pattern

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

There are various techniques to implement the singleton design pattern, but the core concept remains consistent — ensuring that only one instance of an object exists and is accessible throughout the program. In this demo, you’ll use this pattern to create your shopping cart, ensuring you’ll always have precisely one cart for your shopping needs.

- You have 0 order items, at the cost of $0.0
val electronicsShop = ElectronicsShop()
electronicsShop.addItem(electronicsShop.ps5, 1)
electronicsShop.addItem(electronicsShop.xBoxController, 2)
val sportsShop = SportsShop()
sportsShop.addItem(sportsShop.skatingGloves, 2)
sportsShop.addItem(sportsShop.ankleProtector, 2)
- You have 0 order items, at the cost of $0.0
class ShoppingCart private constructor() {
companion object {
  val instance: ShoppingCart by lazy {
    ShoppingCart()
  }
}
private val cart = ShoppingCart.instance
private val cart = ShoppingCart.instance
val cart = ShoppingCart.instance
- You have 4 order items, at the cost of $874.0
See forum comments
Cinema mode Download course materials from Github
Previous: Learning Singleton Pattern Next: Learning Factory Pattern