Design Patterns常用设计模式示例

联合创作 · 2023-09-30 23:17

Design Patterns 是如何使用常用设计模式及示例。

示例:

class MoneyPile {    let value: Int
    var quantity: Int
    var nextPile: MoneyPile?    init(value: Int, quantity: Int, nextPile: MoneyPile?) {        self.value = value        self.quantity = quantity        self.nextPile = nextPile
    }    func canWithdraw(var v: Int) -> Bool {        func canTakeSomeBill(want: Int) -> Bool {            return (want / self.value) > 0
        }        var q = self.quantity        while canTakeSomeBill(v) {            if (q == 0) {                break
            }

            v -= self.value
            q -= 1
        }        if v == 0 {            return true
        } else if let next = self.nextPile {            return next.canWithdraw(v)
        }        return false
    }
}class ATM {
    private var hundred: MoneyPile
    private var fifty: MoneyPile
    private var twenty: MoneyPile
    private var ten: MoneyPile

    private var startPile: MoneyPile {        return self.hundred
    }    init(hundred: MoneyPile, 
           fifty: MoneyPile, 
          twenty: MoneyPile, 
             ten: MoneyPile) {        self.hundred = hundred        self.fifty = fifty        self.twenty = twenty        self.ten = ten
    }    func canWithdraw(value: Int) -> String {        return "Can withdraw: \(self.startPile.canWithdraw(value))"
    }
}
浏览 4
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报