生活随笔
收集整理的這篇文章主要介紹了
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)
轉載于:https://www.cnblogs.com/ls1949/p/8257340.html
總結
以上是生活随笔為你收集整理的swift 设计模式之-责任链模式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。