B/O - Chain of Responsibility
- Category: behavioral
- Type: object
- Motivation: build a chain of object, request from one end and keeps going from object to object till it finds the suitable handler
do {
var bank = Bank(balance: 100)
var paypal = Paypal(balance: 200)
bank.setNext(paypal)
bank.pay(amount: 30)
}
protocol Account
{
var balance: Float {set get}
var sucessor: Account? {set get}
}
extension Account
{
mutating func pay(amount: Float)
{
if canPay(amount) {
balance -= amount
print("\(String(describing: type(of: self))) paid, balance: \(balance)")
} else if var account = sucessor {
account.pay(amount: amount)
} else {
print("none accounts have enought balance")
}
}
func canPay(_ amount: Float) -> Bool
{
amount <= balance
}
mutating func setNext(_ account: Account)
{
sucessor = account
}
}
struct Bank: Account
{
var balance: Float
var sucessor: Account?
}
struct Paypal: Account
{
var balance: Float
var sucessor: Account?
}