转自
原文
// 责任链模式@H_301_20@
// 百度百科:在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。@H_301_20@
// 设计模式分类:行为型模式@H_301_20@
/// 钱堆@H_301_20@
class@H_301_20@ MoneyPile@H_301_20@ {@H_301_20@
/// 价值@H_301_20@
let value: Int
/// 数量@H_301_20@
var@H_301_20@ quantity: Int
/// 下一堆@H_301_20@
var@H_301_20@ nextPile: MoneyPile?
/** 初始化 - parameter value: 价值 - parameter quantity: 数量 - parameter nextPile: 下一堆 - returns: 堆对象 */@H_301_20@
init(value: Int,quantity: Int,nextPile: MoneyPile?) {
self.value = value
self.quantity = quantity
self.nextPile = nextPile
}
/** 判断是否可以提取 - parameter value: 提取值 - returns: true 可以, false 不行 */@H_301_20@
func canWithdraw(value: Int) -> Bool {
var@H_301_20@ v = value
func canTakeSomeBill(want: Int) -> Bool {
return@H_301_20@ (want / self.value) > 0@H_301_20@
}
var@H_301_20@ q = self.quantity
while@H_301_20@ canTakeSomeBill(v) {
if@H_301_20@ q == 0@H_301_20@ {
break@H_301_20@
}
v -= self.value
q -= 1@H_301_20@
}
if@H_301_20@ v == 0@H_301_20@ {
return@H_301_20@ true@H_301_20@
} else@H_301_20@ if@H_301_20@ let next = self.nextPile {
return@H_301_20@ next.canWithdraw(v)
}
return@H_301_20@ false@H_301_20@
}
}
/// ATM取款机@H_301_20@
class@H_301_20@ ATM@H_301_20@ {@H_301_20@
/// 100元堆@H_301_20@
private@H_301_20@ var@H_301_20@ hundred: MoneyPile
/// 50元堆@H_301_20@
private@H_301_20@ var@H_301_20@ fifty: MoneyPile
/// 20元堆@H_301_20@
private@H_301_20@ var@H_301_20@ twenty: MoneyPile
/// 10元堆@H_301_20@
private@H_301_20@ var@H_301_20@ ten: MoneyPile
private@H_301_20@ var@H_301_20@ startPile: MoneyPile {
return@H_301_20@ self.hundred
}
/** 初始化 - parameter hundred: 100元堆 - parameter fifty: 50元堆 - parameter twenty: 20元堆 - parameter ten: 10元堆 - returns: atm对象 */@H_301_20@
init(hundred: MoneyPile,fifty: MoneyPile,twenty: MoneyPile,ten: MoneyPile) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
/** 判断是否可以提取 - parameter value: 提取值 - returns: true 可以, false 不行 */@H_301_20@
func canWithdraw(value: Int) -> String {
return@H_301_20@ "Can withdraw: \(self.startPile.canWithdraw(value))"@H_301_20@
}
}
// 创建一些钱堆, 并将它们链接在一起@H_301_20@
let ten = MoneyPile(value: 10@H_301_20@,quantity: 6@H_301_20@,nextPile: nil)
let twenty = MoneyPile(value: 20@H_301_20@,quantity: 2@H_301_20@,nextPile: ten)
let fifty = MoneyPile(value: 50@H_301_20@,nextPile: twenty)
let hundred = MoneyPile(value: 100@H_301_20@,quantity: 1@H_301_20@,nextPile: fifty)
// 创建atm对象@H_301_20@
var@H_301_20@ atm = ATM(hundred: hundred,fifty: fifty,twenty: twenty,ten: ten)
atm.canWithdraw(310@H_301_20@) // false atm只有300@H_301_20@
atm.canWithdraw(100@H_301_20@) // true 100*1@H_301_20@
atm.canWithdraw(165@H_301_20@) // false atm没有面值5@H_301_20@
atm.canWithdraw(30@H_301_20@) // true 20*1 + 10*1@H_301_20@