
//Handler
class Rescuer {
fileprivate var next: Rescuer?
fileprivate var code = -1
//HandleRequest()
func help(_ code: Int) {
if (self.code == code) {
toHelp()
} else if (next != nil) {
next!.help(code)
}
}
fileprivate func toHelp() {}
}
//ConcreteHandler
class Firefighter: Rescuer {
init(next: Rescuer?) {
super.init()
self.next = next
self.code = 1
}
fileprivate override func toHelp() {
print("call firefighters")
}
}
//ConcreteHandler
class Police: Rescuer {
init(next: Rescuer?) {
super.init()
self.next = next
self.code = 2
}
fileprivate override func toHelp() {
print("call the police")
}
}
//ConcreteHandler
class Ambulance: Rescuer {
init(next: Rescuer?) {
super.init()
self.next = next
self.code = 3
}
fileprivate override func toHelp() {
print("call an ambulance")
}
}
let ambulance = Ambulance(next: nil)
let police = Police(next: ambulance)
let firefighter = Firefighter(next: police)
firefighter.help(1)
//printed: call firefighters
firefighter.help(2)
//printed: call the police
firefighter.help(3)
//printed: call an ambulance