
//Handler
abstract class Rescuer(protected val next: Rescuer?) {
protected var code: Int = 0
//HandleRequest()
fun help(code: Int) {
if (this.code == code) {
toHelp()
} else next?.help(code)
}
abstract fun toHelp()
}
//ConcreteHandler
class Firefighter(next: Rescuer?): Rescuer(next) {
init {
this.code = 1
}
override fun toHelp() {
println("call firefighters")
}
}
//ConcreteHandler
class Police(next: Rescuer?): Rescuer(next) {
init {
this.code = 2
}
override fun toHelp() {
println("call the police")
}
}
//ConcreteHandler
class Ambulance(next: Rescuer?): Rescuer(next) {
init {
this.code = 3
}
override fun toHelp() {
println("call an ambulance")
}
}
//Client
val ambulance = Ambulance(null)
val police = Police(ambulance)
val firefighter = Firefighter(police)
firefighter.help(1)
//printed: call firefighters
firefighter.help(2)
//printed: call the police
firefighter.help(3)
//printed: call an ambulance
| Можно избежать жесткой зависимости отправителя запроса от его получателя, при этом запросом начинает обрабатываться один из нескольких объектов. Объекты-получатели связываются в цепочку, и запрос передается по цепочке, пока какой-то объект его не обработает. |