Explaining the Chain of Responsibility Design Pattern
The chain of responsibility design pattern is a software design pattern in which an object receives a request and passes it along a chain of other objects until the request is handled. This pattern is used to create a chain of objects that can handle a request, and the objects in the chain are organized in a way that allows the request to be handled by the first object that can handle it.
Here is an example of the chain of responsibility design pattern in Swift:
protocol RequestHandler {
var nextHandler: RequestHandler? { get set }
func handleRequest(_ request: String)
}
class RequestHandlerA: RequestHandler {
var nextHandler: RequestHandler?
func handleRequest(_ request: String) {
if request == "request-a" {
print("Request A handled by RequestHandlerA")
} else {
nextHandler?.handleRequest(request)
}
}
}
class RequestHandlerB: RequestHandler {
var nextHandler: RequestHandler?
func handleRequest(_ request: String) {
if request == "request-b" {
print("Request B handled by RequestHandlerB")
} else {
nextHandler?.handleRequest(request)
}
}
}
class RequestHandlerC: RequestHandler {
var nextHandler: RequestHandler?
func handleRequest(_ request: String) {
if request == "request-c" {
print("Request C handled by RequestHandlerC")
} else {
print("Request not handled")
}
}
}
let requestHandlerA = RequestHandlerA()
let requestHandlerB = RequestHandlerB()
let requestHandlerC = RequestHandlerC()
requestHandlerA.nextHandler = requestHandlerB
requestHandlerB.nextHandler = requestHandlerC
requestHandlerA.handleRequest("request-a") // Request A handled by RequestHandlerA
requestHandlerA.handleRequest("request-b") // Request B handled by RequestHandlerB
requestHandlerA.handleRequest("request-c") // Request C handled by RequestHandlerC
requestHandlerA.handleRequest("request-d") // Request not handled