Advanced Object-Oriented Programming in Kotlin

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

Lesson 02: Design Patterns

Implementing Factory 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 Factory.kts in the Starter folder for Lesson 2.

interface PaymentProcessor {
  fun processPayment(amount: Double)
}
// Concrete implementation of PaymentProcessor
class CreditCardProcessor : PaymentProcessor {
  override fun processPayment(amount: Double) {
    println("Processing credit card payment of $$amount.")
    // Additional logic specific to credit card processing
  }
}

// Another concrete implementation of PaymentProcessor
class PayPalProcessor : PaymentProcessor {
  override fun processPayment(amount: Double) {
    println("Processing PayPal payment of $$amount.")
    // Additional logic specific to PayPal processing
  }
}
interface PaymentProcessorFactory {
  fun createPaymentProcessor(): PaymentProcessor
}
// Concrete implementation of PaymentProcessorFactory for Credit Card
class CreditCardProcessorFactory : PaymentProcessorFactory {
  override fun createPaymentProcessor(): PaymentProcessor {
    return CreditCardProcessor()
  }
}

// Concrete implementation of PaymentProcessorFactory for PayPal
class PayPalProcessorFactory : PaymentProcessorFactory {
  override fun createPaymentProcessor(): PaymentProcessor {
    return PayPalProcessor()
   }
}
val customerPayingWithCC = false
// Customer wants to use CC
val paymentProcessorFactory = if (customerPayingWithCC) {
  CreditCardProcessorFactory()
} else {
  PayPalProcessorFactory()
}
val paymentProcessor: PaymentProcessor = paymentProcessorFactory.createPaymentProcessor()
paymentProcessor.processPayment(cart.getTotalCostOfItems())
- You have 4 order items, at the cost of $874.0
Processing PayPal payment of $874.0.
- You have 4 order items, at the cost of $874.0
Processing credit card payment of $874.0.
See forum comments
Cinema mode Download course materials from Github
Previous: Learning Factory Pattern Next: Learning Observer Pattern