責任鏈
在物件導向的設計中,責任鏈模式是一種由
command
物件和一系列processing
物件組成的設計模式。每個processing
物件都包含定義它可以處理的命令物件型別的邏輯; 其餘的傳遞給鏈中的下一個processing
物件。還有一種機制可以將新的processing
物件新增到該鏈的末尾。維基百科
建立構成責任鏈的類。
首先,我們為所有 processing
物件建立一個介面。
protocol PurchasePower {
var allowable : Float { get }
var role : String { get }
var successor : PurchasePower? { get set }
}
extension PurchasePower {
func process(request : PurchaseRequest){
if request.amount < self.allowable {
print(self.role + " will approve $ \(request.amount) for \(request.purpose)")
} else if successor != nil {
successor?.process(request: request)
}
}
}
然後我們建立 command
物件。
struct PurchaseRequest {
var amount : Float
var purpose : String
}
最後,建立構成責任鏈的物件。
class ManagerPower : PurchasePower {
var allowable: Float = 20
var role : String = "Manager"
var successor: PurchasePower?
}
class DirectorPower : PurchasePower {
var allowable: Float = 100
var role = "Director"
var successor: PurchasePower?
}
class PresidentPower : PurchasePower {
var allowable: Float = 5000
var role = "President"
var successor: PurchasePower?
}
啟動並將它連結在一起:
let manager = ManagerPower()
let director = DirectorPower()
let president = PresidentPower()
manager.successor = director
director.successor = president
這裡連結物件的機制是屬性訪問
建立執行它的請求:
manager.process(request: PurchaseRequest(amount: 2, purpose: "buying a pen")) // Manager will approve $ 2.0 for buying a pen
manager.process(request: PurchaseRequest(amount: 90, purpose: "buying a printer")) // Director will approve $ 90.0 for buying a printer
manager.process(request: PurchaseRequest(amount: 2000, purpose: "invest in stock")) // President will approve $ 2000.0 for invest in stock