1 from abc import ABCMeta, abstractmethod
2
3
4 -class ChainLink(object, metaclass=ABCMeta):
5 """
6 Abstract ChainLink object as part of the Chain of Responsibility pattern.
7
8 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage}
9 - External Chain of Responsibility Pattern documentation: U{https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern}
10 """
12 """
13 Initialize a new ChainLink instance.
14 """
15 self.successor = None
16
18 """
19 Set a chain link to call if this chain link fails.
20
21 @param successor: The chain link to call if this chain link fails.
22 @type successor: ChainLink
23 """
24 self.successor = successor
25
27 """
28 Have this chain links successor handle a request.
29
30 @param request: The request to handle.
31 """
32 return self.successor.handle(request)
33
34 @abstractmethod
36 """
37 Handle a request.
38
39 @param request: The request to handle.
40 """
41 pass
42
43
44 -class Chain(object, metaclass=ABCMeta):
45 """
46 Abstract Chain class as part of the Chain of Responsibility pattern.
47
48 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage}
49 - External Chain of Responsibility Pattern documentation: U{https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern}
50 """
52 """
53 Initialize a new Chain instance.
54
55 @param chainlink: The starting chain link.
56 """
57 self.chainlink = chainlink
58
60 """
61 Handle a request.
62
63 @param request: The request to handle.
64 """
65 try:
66 return self.chainlink.handle(request)
67 except AttributeError:
68 return self.fail()
69
70 @abstractmethod
72 """
73 The method to call when the chain could not handle a request.
74 """
75 pass
76