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
 

About Author

This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions