zoukankan      html  css  js  c++  java
  • swift 设计模式之-责任链模式

     

    1. //每个对象持有对下一个对象的引用,这样就会形成一条链,请求在这条链上传递,直到某一对象决定处理该请求。但是发出者并不清楚到底最终那个对象会处理该请求,所以,责任链模式可以实现,在隐瞒客户端的情况下,对系统进行动态的调整。
    2. 如下关于一个ATM取款机的例子,来告知是否可以取款到相应金额。
    3. final class MoneyPil{
    4.     let value : Int
    5.     var quantity:Int
    6.     var nextPile:MoneyPil?
    7.     init(value:Int,quantitly:Int,nextpile:MoneyPil?) {
    8.         self.value = value
    9.         self.quantity = quantitly
    10.         self.nextPile = nextpile
    11.     }
    12.  
    13.     func canWithDraw(amount:Int) -> Bool {
    14.         var amount = amount
    15.         func canTakeSomeBill(want:Int)->Bool{
    16.             return (want/self.value)>0}
    17.         var quantity = self.quantity
    18.         while canTakeSomeBill(want: amount) {
    19.             if quantity == 0{break}
    20.             amount -= self.value
    21.             quantity -= 1
    22.         }
    23.             guard amount > 0 else{return true}
    24.             if let next = self.nextPile{
    25.                 return next.canWithDraw(amount:amount)
    26.             }
    27.             return false
    28.     }
    29. }
    30. final class ATM {
    31.     private var hundred:MoneyPil
    32.     private var fifty:MoneyPil
    33.     private var twenty:MoneyPil
    34.     private var ten:MoneyPil
    35.     private var startoile:MoneyPil{
    36.         return self.hundred
    37.     }
    38.     init(hundred: MoneyPil,
    39.            fifty: MoneyPil,
    40.           twenty: MoneyPil,
    41.              ten: MoneyPil) {
    42.         self.hundred = hundred
    43.         self.fifty   = fifty
    44.         self.twenty  = twenty
    45.         self.ten     = ten
    46.     }
    47.     func canWithDraw(amount:Int)->String{
    48.         return "Can withdraw:(self.startoile.canWithDraw(amount: amount))"
    49.     }
    1. }
    2. let ten = MoneyPil(value:10, quantitly:6, nextpile: nil)
    3. let twenty = MoneyPil(value: 20, quantitly: 2, nextpile: ten)
    4. let fifty = MoneyPil(value: 50, quantitly: 2, nextpile: twenty)
    5. let hundred = MoneyPil(value: 100, quantitly: 1, nextpile: fifty)
    1. var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
    2. atm.canWithDraw(amount: 100)
    3. atm.canWithDraw(amount: 310)
    4. atm.canWithDraw(amount: 165)
    5. atm.canWithDraw(amount: 70)
  • 相关阅读:
    解决无法安装Microsoft .Net Framework 3.5
    day11-15,装饰器
    Xmanager Power Suit 6.0.0009 最新版注册激活
    eth
    MySql 8.0 版本使用navicat连不上解决
    day11
    Mybatis使用规则
    nginx的基本配置
    Mybatis分页插件PageHelper使用
    dubbo的使用
  • 原文地址:https://www.cnblogs.com/ls1949/p/8257340.html
Copyright © 2011-2022 走看看