Completed
Push — master ( 336d1a...d357d6 )
by Konstantinos
20s queued 13s
created

software_patterns.handler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 21
dl 0
loc 43
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A AbstractHandler.handle() 0 6 2
A Handler.handle() 0 3 1
A Handler.set_next() 0 3 1
A AbstractHandler.set_next() 0 6 1
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