Explain Chain of Responsibility Pattern
Explain Chain of Responsibility Pattern
:::info[TL/DR]
The Chain of Responsibility Pattern allows multiple objects to handle a request, passing it along a chain until one of the objects handles it. It
is useful for processing events where different handlers act based on specific criteria.
:::
Concept Overview
The Chain of Responsibility Pattern is a behavioral design pattern that decouples the sender of a request from its receiver. Multiple
handlers are linked, and each handler decides either to process the request or pass it to the next handler in the chain.
Key components:
3. Concrete Handlers: Each handler processes the request or forwards it to the next handler.
Playground Example
Below is an example based on a coin validation system:
import Foundation
// Example Usage
let pennyHandler = CoinHandler(coinType: Penny.self)
let quarterHandler = CoinHandler(coinType: Quarter.self)
pennyHandler.next = quarterHandler
How It Works:
Client: Sends the unknownCoin to the first handler ( pennyHandler ).
Handlers: Each CoinHandler validates the coin. If it cannot handle the request, it passes the request to the next handler in the chain.
When to Use
Event handling: When multiple objects might handle a request, and the specific handler is not known in advance.
Decoupling: When you want to decouple senders from receivers and chain multiple handlers together.
When to Be Careful
Long chains: A long chain of handlers can impact performance and make debugging more complex.
:::tip[In Bullets]
The Chain of Responsibility Pattern allows requests to be passed along a chain of handlers until one processes it.
Useful for event handling and decoupling sender and receiver logic.
:::