Skip to content

Commit 529dac4

Browse files
committed
Merge pull request ochococo#19 from tomkowz/master
Modified Chain of responsibility
2 parents 3f32977 + 43d3574 commit 529dac4

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

README.markdown

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,82 @@ computer.openDoors(doors)
559559
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
560560
561561
##🚧 Chain Of Responsibility
562+
```swift
563+
class MoneyPile {
564+
let value: Int
565+
var quantity: Int
566+
var nextPile: MoneyPile?
567+
568+
init(value: Int, quantity: Int, nextPile: MoneyPile?) {
569+
self.value = value
570+
self.quantity = quantity
571+
self.nextPile = nextPile
572+
}
573+
574+
func canWithdraw(var v: Int) -> Bool {
575+
func canTakeSomeBill(want: Int) -> Bool {
576+
return (want / self.value) > 0
577+
}
578+
579+
var q = self.quantity
580+
while canTakeSomeBill(v) {
581+
if (q == 0) {
582+
break
583+
}
584+
585+
v -= self.value
586+
q--
587+
}
588+
589+
if (v == 0) {
590+
return true
591+
} else if let next = self.nextPile {
592+
return next.canWithdraw(v)
593+
}
594+
595+
return false
596+
}
597+
}
598+
599+
class ATM {
600+
private var hundred: MoneyPile
601+
private var fifty: MoneyPile
602+
private var twenty: MoneyPile
603+
private var ten: MoneyPile
604+
605+
private var startPile: MoneyPile {
606+
return self.hundred
607+
}
608+
609+
init(hundred: MoneyPile, fifty: MoneyPile, twenty: MoneyPile, ten: MoneyPile) {
610+
self.hundred = hundred
611+
self.fifty = fifty
612+
self.twenty = twenty
613+
self.ten = ten
614+
}
615+
616+
func canWithdraw(value: Int) -> String {
617+
return "Can withdraw: \(self.startPile.canWithdraw(value))"
618+
}
619+
}
620+
```
621+
622+
**Usage:**
623+
```swift
624+
/// Create piles of money and link them together 10 < 20 < 50 < 100
625+
var ten = MoneyPile(value: 10, quantity: 6, nextPile: nil)
626+
var twenty = MoneyPile(value: 20, quantity: 2, nextPile: ten)
627+
var fifty = MoneyPile(value: 50, quantity: 2, nextPile: twenty)
628+
var hundred = MoneyPile(value: 100, quantity: 1, nextPile: fifty)
629+
630+
/// build atm
631+
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
632+
atm.canWithdraw(310) /// Cannot because ATM has only 300
633+
atm.canWithdraw(100) /// Can withdraw - 1x100
634+
atm.canWithdraw(165) /// Cannot withdraw because ATM doesn't has bill with value of 5
635+
atm.canWithdraw(30) /// Can withdraw - 1x20, 2x10
636+
```
637+
562638
##👫 Command
563639

564640
```swift

0 commit comments

Comments
 (0)