-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchain_final.py
More file actions
executable file
·50 lines (37 loc) · 1.62 KB
/
chain_final.py
File metadata and controls
executable file
·50 lines (37 loc) · 1.62 KB
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
class Handler: #Abstract handler
"""Abstract Handler"""
def __init__(self, successor):
self._successor = successor # Define who is the next handler
def handle(self, request):
handled = self._handle(request) #If handled, stop here
#Otherwise, keep going
if not handled:
self._successor.handle(request)
def _handle(self, request):
raise NotImplementedError('Must provide implementation in subclass!')
class ConcreteHandler1(Handler): # Inherits from the abstract handler
"""Concrete handler 1"""
def _handle(self, request):
if 0 < request <= 10: # Provide a condition for handling
print("Request {} handled in handler 1".format(request))
return True # Indicates that the request has been handled
class DefaultHandler(Handler): # Inherits from the abstract handler
"""Default handler"""
def _handle(self, request):
"""If there is no handler available"""
#No condition checking since this is a default handler
print("End of chain, no handler for {}".format(request))
return True # Indicates that the request has been handled
class Client: # Using handlers
def __init__(self):
self.handler = ConcreteHandler1(DefaultHandler(None)) # Create handlers and use them in a sequence you want
# Note that the default handler has no successor
def delegate(self, requests): # Send your requests one at a time for handlers to handle
for request in requests:
self.handler.handle(request)
# Create a client
c = Client()
# Create requests
requests = [2, 5, 30]
# Send the requests
c.delegate(requests)