| Total Complexity | 5 |
| Total Lines | 43 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | from __future__ import annotations |
||
| 2 | |||
| 3 | from abc import ABC, abstractmethod |
||
| 4 | from typing import Any, Optional |
||
| 5 | |||
| 6 | |||
| 7 | class Handler(ABC): |
||
| 8 | """ |
||
| 9 | The Handler interface declares a method for building the chain of handlers. |
||
| 10 | It also declares a method for executing a request. |
||
| 11 | """ |
||
| 12 | |||
| 13 | @abstractmethod |
||
| 14 | def set_next(self, handler: Handler) -> Handler: |
||
| 15 | pass |
||
| 16 | |||
| 17 | @abstractmethod |
||
| 18 | def handle(self, request) -> Optional[str]: |
||
| 19 | pass |
||
| 20 | |||
| 21 | |||
| 22 | class AbstractHandler(Handler): |
||
| 23 | """ |
||
| 24 | The default chaining behavior can be implemented inside a base handler |
||
| 25 | class. |
||
| 26 | """ |
||
| 27 | |||
| 28 | _next_handler: Optional[Handler] = None |
||
| 29 | |||
| 30 | def set_next(self, handler: Handler) -> Handler: |
||
| 31 | self._next_handler = handler |
||
| 32 | # Returning a handler from here will let us link handlers in a |
||
| 33 | # convenient way like this: |
||
| 34 | # monkey.set_next(squirrel).set_next(dog) |
||
| 35 | return handler |
||
| 36 | |||
| 37 | @abstractmethod |
||
| 38 | def handle(self, request: Any) -> Optional[str]: |
||
| 39 | if self._next_handler: |
||
| 40 | return self._next_handler.handle(request) |
||
| 41 | |||
| 42 | return None |
||
| 43 |