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

software_patterns.handler.Handler.set_next()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 2
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