|
| 1 | +--- |
| 2 | +file: behavioral/chain_of_responsibility.py |
| 3 | +chunk: behavioral_chain_of_responsibility.md |
| 4 | +--- |
| 5 | + |
| 6 | +```python |
| 7 | +""" |
| 8 | +Behavioral Pattern: Chain of Responsibility |
| 9 | +
|
| 10 | +Lets you pass requests along a chain of handlers, where each handler decides |
| 11 | +whether to process the request or pass it along. |
| 12 | +Promotes loose coupling between sender and receiver. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | +from abc import ABC, abstractmethod |
| 17 | +from typing import Optional |
| 18 | + |
| 19 | +class Handler(ABC): |
| 20 | + """Base Handler class with chaining support.""" |
| 21 | + |
| 22 | + _next_handler: Optional[Handler] = None |
| 23 | + |
| 24 | + def set_next(self, handler: Handler) -> Handler: |
| 25 | + self._next_handler = handler |
| 26 | + return handler |
| 27 | + |
| 28 | + @abstractmethod |
| 29 | + def handle(self, request: str) -> Optional[str]: |
| 30 | + pass |
| 31 | + |
| 32 | +class MonkeyHandler(Handler): |
| 33 | + def handle(self, request: str) -> Optional[str]: |
| 34 | + if request == "Banana": |
| 35 | + return "Monkey: I'll eat the Banana." |
| 36 | + elif self._next_handler: |
| 37 | + return self._next_handler.handle(request) |
| 38 | + return None |
| 39 | + |
| 40 | +class SquirrelHandler(Handler): |
| 41 | + def handle(self, request: str) -> Optional[str]: |
| 42 | + if request == "Nut": |
| 43 | + return "Squirrel: I'll eat the Nut." |
| 44 | + elif self._next_handler: |
| 45 | + return self._next_handler.handle(request) |
| 46 | + return None |
| 47 | + |
| 48 | +class DogHandler(Handler): |
| 49 | + def handle(self, request: str) -> Optional[str]: |
| 50 | + if request == "Meat": |
| 51 | + return "Dog: I'll eat the Meat." |
| 52 | + elif self._next_handler: |
| 53 | + return self._next_handler.handle(request) |
| 54 | + return None |
| 55 | + |
| 56 | +# Example usage |
| 57 | +if __name__ == "__main__": |
| 58 | + monkey = MonkeyHandler() |
| 59 | + squirrel = SquirrelHandler() |
| 60 | + dog = DogHandler() |
| 61 | + |
| 62 | + monkey.set_next(squirrel).set_next(dog) |
| 63 | + |
| 64 | + for food in ["Nut", "Banana", "Meat", "Apple"]: |
| 65 | + print(f"Client: Who wants a {food}?") |
| 66 | + result = monkey.handle(food) |
| 67 | + if result: |
| 68 | + print(result) |
| 69 | + else: |
| 70 | + print(f"No one wants the {food}.") |
| 71 | +``` |
| 72 | + |
| 73 | +## Summary |
| 74 | +Implementation of the Chain of Responsibility pattern in Python. |
| 75 | + |
| 76 | +## Docstrings |
| 77 | +- Base Handler class with chaining support. |
| 78 | +- Sets the next handler in the chain and returns the next handler. |
| 79 | +- Abstract method to handle requests. Must be implemented by subclasses. |
| 80 | +- Handler for monkeys that can eat bananas. |
| 81 | +- Handler for squirrels that can eat nuts. |
| 82 | +- Handler for dogs that can eat meat. |
| 83 | + |
0 commit comments