-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathchain_of_responsibility_concept.py
57 lines (47 loc) · 1.46 KB
/
chain_of_responsibility_concept.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# pylint: disable=too-few-public-methods
"The Chain Of Responsibility Pattern Concept"
import random
from abc import ABCMeta, abstractmethod
class IHandler(metaclass=ABCMeta):
"The Handler Interface that the Successors should implement"
@staticmethod
@abstractmethod
def handle(payload):
"A method to implement"
class Successor1(IHandler):
"A Concrete Handler"
@staticmethod
def handle(payload):
print(f"Successor1 payload = {payload}")
test = random.randint(1, 2)
if test == 1:
payload = payload + 1
payload = Successor1().handle(payload)
if test == 2:
payload = payload - 1
payload = Successor2().handle(payload)
return payload
class Successor2(IHandler):
"A Concrete Handler"
@staticmethod
def handle(payload):
print(f"Successor2 payload = {payload}")
test = random.randint(1, 3)
if test == 1:
payload = payload * 2
payload = Successor1().handle(payload)
if test == 2:
payload = payload / 2
payload = Successor2().handle(payload)
return payload
class Chain():
"A chain with a default first successor"
@staticmethod
def start(payload):
"Setting the first successor that will modify the payload"
return Successor1().handle(payload)
# The Client
CHAIN = Chain()
PAYLOAD = 1
OUT = CHAIN.start(PAYLOAD)
print(f"Finished result = {OUT}")