Advanced Object-Oriented Programming in Kotlin

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

Lesson 02: Design Patterns

Implementing Observer 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

Start by opening the Kotlin playground in your browser. Download the course material from the GitHub link at the side of the video. Copy and paste the code from Observer.kts in the Starter folder for Lesson 2.

- You have 1 order items, at the cost of $24.0
interface IObserver {
  fun update(product: Product)
}
interface IObservable {
  val observers: ArrayList<IObserver>

  fun add(observer: IObserver) {
    observers.add(observer)
  }

  fun remove(observer: IObserver) {
    observers.remove(observer)
  }

  fun sendUpdateEvent(product: Product) {
    observers.forEach { it.update(product) }
  }
}
class Product(name: String, price: Double) : IObservable {
  override val observers: ArrayList<IObserver> = ArrayList()

  var name = name
    set(value) {
      field = value
      sendUpdateEvent(this)
    }

  var price = price
    set(value) {
      field = value
      sendUpdateEvent(this)
    }
}
class ShoppingCart private constructor() : IObserver {
override fun update(product: Product) {
  orderItems.find { it.getProduct() == product }?.product(product)
}
orderItem.getProduct().add(this)
skatingGloves.price = 6.0
- You have 1 order items, at the cost of $12.0
See forum comments
Cinema mode Download course materials from Github
Previous: Learning Observer Pattern Next: Conclusion