Wednesday, August 16, 2023

Chain Of Responsibility in Python...

 In this design pattern, there are some sorts of executors of a command tied in a chain - at different levels. Depending upon the complexity of the task, the command is handled at different levels. Each receiver is well aware of if he can handle the command. If he can't he simply passes the buck to the next person in the chain. Once the command reaches the highest level of the chain, it must be handled there as there is no more successor after the highest authority.

The idea is that the command is always delivered at the lowest level of the chain and then it moves forward - one step at a time till it is handled at one such level.

Here is the class diagram of the Chain of Responsibility design pattern.


Here goes the source code of the chain of responsibility implemented in Python...

from abc import ABC, abstractmethod


class ICommand(ABC):
def __init__(self, level):
self.level = level


class CommandReceiver(ABC):
def __init__(self, successor):
self.successor = successor


@abstractmethod
def handleCommandImpl(self, command):
pass

def handleCommand(self, command):
retType = self.handleCommandImpl(command)
if self.successor != None and retType == False:
self.successor.handleCommand(command)
else:
return



class ReceiverLevel1(CommandReceiver):
def __init__(self, successor):
self.successor = successor

def handleCommandImpl(self, command):
if command.level == 1:
print("The Command is handled at level 1")
return True
else:
print("Forwarding the command from level 1 to level 2")
return False


class ReceiverLevel2(CommandReceiver):
def __init__(self, successor):
self.successor = successor

def handleCommandImpl(self, command):
if command.level == 2:
print("The Command is handled at level 2")
return True
else:
print("Forwarding the command from level 2 to level 3")
return False


class ReceiverLevel3(CommandReceiver):
def __init__(self, successor):
self.successor = successor

def handleCommandImpl(self, command):
if command.level == 3:
print("The Command is handled at level 3")
return True
else:
print("Last level... The Command has to be managed here...")
return False


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
commandLevel1 = ICommand(1)
commandLevel2 = ICommand(2)
commandLevel3 = ICommand(3)

receiverLevel3 = ReceiverLevel3(None)
receiverLevel2 = ReceiverLevel2(receiverLevel3)
receiverLevel1 = ReceiverLevel1(receiverLevel2)

receiverLevel1.handleCommand(commandLevel3)


No comments: