To illustrate how the Chain of Responsibility pattern works, let's look at a simple example in Python. Suppose you have a chat application that allows users to send messages to each other. You want to implement some filters that can modify or reject the messages based on some criteria, such as profanity, spam, or length. You can use the Chain of Responsibility pattern to create a chain of filters that each check and process the message before passing it to the next filter.
First, you need to define an abstract base class for the filters, which has a method to handle the message and a reference to the next filter in the chain.
class Filter:
def __init__(self, next_filter=None):
self.next_filter = next_filter
def handle(self, message):
raise NotImplementedError
Next, you need to implement some concrete subclasses of Filter that perform different types of filtering. For example, you can have a ProfanityFilter that replaces any swear words with asterisks, a SpamFilter that rejects any messages that contain links or ads, and a LengthFilter that truncates any messages that are too long.
class ProfanityFilter(Filter):
def handle(self, message):
# replace swear words with asterisks
message = message.replace("bad", "***")
message = message.replace("word", "****")
# pass the message to the next filter if any
if self.next_filter:
return self.next_filter.handle(message)
# return the message otherwise
else:
return message
class SpamFilter(Filter):
def handle(self, message):
# reject any messages that contain links or ads
if "http" in message or "buy" in message:
return "Message rejected: spam detected"
# pass the message to the next filter if any
if self.next_filter:
return self.next_filter.handle(message)
# return the message otherwise
else:
return message
class LengthFilter(Filter):
def handle(self, message):
# truncate any messages that are longer than 10 characters
if len(message) > 10:
message = message[:10] + "..."
# pass the message to the next filter if any
if self.next_filter:
return self.next_filter.handle(message)
# return the message otherwise
else:
return message
Finally, you need to create the chain of filters by linking them together. You can do this by passing the next filter as an argument to the constructor of the previous filter. For example, you can create a chain that consists of the ProfanityFilter, the SpamFilter, and the LengthFilter, in that order. filter_chain = ProfanityFilter(SpamFilter(LengthFilter())) Now, you can use the filter_chain object to handle any message that is sent by the users. For example, if a user sends a message that says "This is a bad word", the filter_chain will return "This is a *** ****...".
message = "This is a bad word"
filtered_message = filter_chain.handle(message)
print(filtered_message) # This is a *** ****...