Answer 1

The chain of responsibility pattern inside Python allows us to build an application with loose coupling in mind. This is achieved by passing a received request through a chain of objects inside the software.

The following code snippet shows the implementation of the chain of responsibility pattern inside Python:

import abc

class Handler(metaclass=abc.ABCMeta):
"""Handler provides an interface to build handlers."""

def __init__(self, handler=None):
"""Initialize the handler.

Keyword arguments:
handler -- The next handler object to be called
"""

self._next_handler = handler

@abc.abstractmethod
def handler(self, data):
"""The handler abstract method.

Keyword arguments:
data -- The data to be processed by the handler
"""

pass

class StringHandler(Handler):
"""String type object handler."""

def handler(self, data):
if type(data) is str:
print("Stringt type data found.")
elif self._next_handler is not None:
self._next_handler.handler(data)
else:
raise Exception("Unable to find a suitable handler for data.")

class IntegerHandler(Handler):
"""Integer type object handler."""

def handler(self, data):
if type(data) is int:
print("Integer type data found")
elif self._next_handler is not None:
self._next_handler.handler(data)
else:
raise Exception("Unable to find a suitable handler for data.")

if __name__ == '__main__':
int_handler = IntegerHandler()
str_handler = StringHandler(int_handler)
str_handler.handler(2)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.96.105