Skip to content

Commit 64b3a0c

Browse files
committed
Make handlers a bit different, rename Default to Fallback
1 parent 03e8e32 commit 64b3a0c

1 file changed

Lines changed: 27 additions & 10 deletions

File tree

behavioral/chain.py

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,36 +48,53 @@ def compare(self, request):
4848

4949

5050
class ConcreteHandler0(Handler):
51-
def compare(self, request):
51+
"""Each handler can be different.
52+
Be simple and static...
53+
"""
54+
55+
@staticmethod
56+
def compare(request):
5257
if 0 <= request < 10:
53-
print('request {} handled in handler 0'.format(request))
58+
print("request {} handled in handler 0".format(request))
5459
return True
5560

5661

5762
class ConcreteHandler1(Handler):
63+
"""... With it's own internal state"""
64+
65+
start, end = 10, 20
66+
5867
def compare(self, request):
59-
if 10 <= request < 20:
60-
print('request {} handled in handler 1'.format(request))
68+
if self.start <= request < self.end:
69+
print("request {} handled in handler 1".format(request))
6170
return True
6271

6372

6473
class ConcreteHandler2(Handler):
74+
"""... With helper methods."""
75+
6576
def compare(self, request):
66-
if 20 <= request < 30:
67-
print('request {} handled in handler 2'.format(request))
77+
start, end = self.get_interval_from_db()
78+
if start <= request < end:
79+
print("request {} handled in handler 2".format(request))
6880
return True
6981

82+
@staticmethod
83+
def get_interval_from_db():
84+
return (20, 30)
7085

71-
class DefaultHandler(Handler):
72-
def compare(self, request):
73-
print('end of chain, no handler for {}'.format(request))
86+
87+
class FallbackHandler(Handler):
88+
@staticmethod
89+
def compare(request):
90+
print("end of chain, no handler for {}".format(request))
7491
return False
7592

7693

7794
if __name__ == "__main__":
7895
h0 = ConcreteHandler0()
7996
h1 = ConcreteHandler1()
80-
h2 = ConcreteHandler2(DefaultHandler())
97+
h2 = ConcreteHandler2(FallbackHandler())
8198
h0.successor = h1
8299
h1.successor = h2
83100

0 commit comments

Comments
 (0)