-
Notifications
You must be signed in to change notification settings - Fork 0
Open Closed principle
Devrath edited this page Dec 31, 2023
·
9 revisions
π²πΎπ½ππ΄π½ππ |
---|
What is Open Closed Principle ? |
Code |
Structure |
How open/closed principle is used here |
A class must be open for extension and closed for modification
Payment.kt
interface Payment {
fun processPayment(int : Int) : String
}
CreditCard.kt
class CreditCard : Payment {
override fun processPayment(int: Int): String {
// Logic for processing the payment of credit card
return "Result of acknowledgement"
}
}
DebitCard.kt
class DebitCard : Payment {
override fun processPayment(int: Int): String {
// Logic for processing the payment of debit card
return "Result of acknowledgement"
}
}
PaymentProcessor.kt
class PaymentProcessor {
private val paymentMethods : MutableList<Payment> = arrayListOf()
/**
* Add a new payment method
*/
fun addPaymentMethod(payment : Payment){
paymentMethods.add(payment)
}
/**
* Process the payment
*/
fun processPayment(amount : Int){
for (payment in paymentMethods){
val result = payment.processPayment(amount);
println(result)
}
}
}
Demo
fun demo() {
// Amount to pay
val amountToPay = 100
// We shall assume that we are paying via credit card
val creditCardPayment = CreditCard()
// Payment processor is used to process the payments
val paymentProcessor = PaymentProcessor()
// Add the payment method
paymentProcessor.addPaymentMethod(creditCardPayment)
// Process the payment
paymentProcessor.processPayment(amountToPay)
}
- We define the
Payment
interface. - We have
CreditCard
andDebitCard
implementations for thePayment
specific for that type. - We have a Payment processor class that handles the payment and initiates it by redirecting it to appropriate implementations.
- Suppose you need to add a new payment method. In that case, you can create a new class that implements the
Payment
interface without modifying the existing code for thePaymentProcessor
or any other payment method classes. - This adheres to the Open/Closed Principle, allowing the system to be easily extended with new functionality (new payment methods) without modifying existing code.