责任链

在面向对象的设计中,责任链模式是一种由 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