swift 设计模式之-责任链模式
- //每个对象持有对下一个对象的引用,这样就会形成一条链,请求在这条链上传递,直到某一对象决定处理该请求。但是发出者并不清楚到底最终那个对象会处理该请求,所以,责任链模式可以实现,在隐瞒客户端的情况下,对系统进行动态的调整。
- 如下关于一个ATM取款机的例子,来告知是否可以取款到相应金额。
- final class MoneyPil{
- let value : Int
- var quantity:Int
- var nextPile:MoneyPil?
- init(value:Int,quantitly:Int,nextpile:MoneyPil?) {
- self.value = value
- self.quantity = quantitly
- self.nextPile = nextpile
- }
- func canWithDraw(amount:Int) -> Bool {
- var amount = amount
- func canTakeSomeBill(want:Int)->Bool{
- return (want/self.value)>0}
- var quantity = self.quantity
- while canTakeSomeBill(want: amount) {
- if quantity == 0{break}
- amount -= self.value
- quantity -= 1
- }
- guard amount > 0 else{return true}
- if let next = self.nextPile{
- return next.canWithDraw(amount:amount)
- }
- return false
- }
- }
- final class ATM {
- private var hundred:MoneyPil
- private var fifty:MoneyPil
- private var twenty:MoneyPil
- private var ten:MoneyPil
- private var startoile:MoneyPil{
- return self.hundred
- }
- init(hundred: MoneyPil,
- fifty: MoneyPil,
- twenty: MoneyPil,
- ten: MoneyPil) {
- self.hundred = hundred
- self.fifty = fifty
- self.twenty = twenty
- self.ten = ten
- }
- func canWithDraw(amount:Int)->String{
- return "Can withdraw:\(self.startoile.canWithDraw(amount: amount))"
- }
- }
- let ten = MoneyPil(value:10, quantitly:6, nextpile: nil)
- let twenty = MoneyPil(value: 20, quantitly: 2, nextpile: ten)
- let fifty = MoneyPil(value: 50, quantitly: 2, nextpile: twenty)
- let hundred = MoneyPil(value: 100, quantitly: 1, nextpile: fifty)
- var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
- atm.canWithDraw(amount: 100)
- atm.canWithDraw(amount: 310)
- atm.canWithDraw(amount: 165)
- atm.canWithDraw(amount: 70)