Advanced Object-Oriented Programming in Kotlin

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

Lesson 03: Single Responsibility & Open-Closed Principles

Implementing Open-Closed Principle

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

The Open-Closed Principle states that a software entity should be open for extension but closed for modification. In this demo, you’ll use this principle to enhance the quality of your e-commerce app.

Processing payment using Stripe.
Payment successful. Order has been processed.
interface PaymentGateway {
  fun processPayment(shoppingCart: ShoppingCart): Boolean
}
class StripePaymentGateway : PaymentGateway {
  override fun processPayment(shoppingCart: ShoppingCart): Boolean {
    // Logic to process payment using Stripe
    println("Processing payment using Stripe.")
    // Actual payment processing logic with Stripe API would go here
    return true
  }
}
class PaypalPaymentGateway : PaymentGateway {
  override fun processPayment(shoppingCart: ShoppingCart): Boolean {
    // Logic to process payment using PayPal
    println("Processing payment using PayPal.")
    // Actual payment processing logic with Paypal API would go here
    return true
  }
}
class CheckoutService(private val paymentGateway: PaymentGateway) {
  fun processOrderPayment(shoppingCart: ShoppingCart) {
    val paymentResult = paymentGateway.processPayment(shoppingCart)

    if (paymentResult) {
      println("Payment successful. Order has been processed.")
    } else {
      println("Payment failed for order.")
    }
  }
}
enum class PaymentGatewayType {
  STRIPE,
  PAYPAL
}
val selectedGateway = PaymentGatewayType.STRIPE

 // Creating an instance of the selected payment gateway
 val paymentGateway = when (selectedGateway) {
 PaymentGatewayType.STRIPE -> StripePaymentGateway()
 PaymentGatewayType.PAYPAL -> PaypalPaymentGateway()
 }

 // Using the CheckoutService with the selected payment gateway
 val checkoutService = CheckoutService(paymentGateway)
Processing payment using Stripe.
Payment successful. Order has been processed.
Processing payment using PayPal.
Payment successful. Order has been processed.
See forum comments
Cinema mode Download course materials from Github
Previous: Learning Open-Closed Principle Next: Conclusion