Chain of Responsibility Pattern in kotlin | Design Patterns

Chain of responsibility pattern is used to achieve loose coupling in software design where a request from client is passed to a chain of objects to process them. Later, the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not.


package behavioral
class MoneyPile(val value: Int, var quantity: Int, var nextPile: MoneyPile?) {
    fun canTakeSomeBill(want: Int): Boolean = (want / this.value) > 0
    fun canWithdraw(withdrawAmount: Int): Boolean {
        var amount = withdrawAmount
        var quantity = this.quantity
        while (canTakeSomeBill(want = amount)) {
            if (quantity == 0) {
                break
            }
            amount -= this.value
            quantity -= 1
        }
        if (amount <= 0) {
            return true
        }
        nextPile?.let {
            return it.canWithdraw(withdrawAmount = amount)
        }
        return false
    }
}
class ATM(val moneyPile: MoneyPile) {
    fun canWithdraw(amount: Int) = println("Can withdraw: ${moneyPile.canWithdraw(withdrawAmount = amount)}")
}
fun main(args: Array<String>) {
    val ten = MoneyPile(value = 10, quantity = 6, nextPile = null) // 60
    val twenty = MoneyPile(value = 20, quantity = 2, nextPile = ten) // 40
    val fifty = MoneyPile(value = 50, quantity = 2, nextPile = twenty) // 100
    val hundred = MoneyPile(value = 100, quantity = 1, nextPile = fifty) // 100
    val atm = ATM(moneyPile = hundred)
    atm.canWithdraw(amount = 310) // Cannot because behavioral.ATM has only 300
    atm.canWithdraw(amount = 100) // Can withdraw - 1x100
    atm.canWithdraw(amount = 165) // Cannot withdraw because behavioral.ATM doesn't has bill with value of 5
    atm.canWithdraw(amount = 30)  // Can withdraw - 1x20, 2x10
}			

 
Join My Facebook Group
Join Group
 
aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group