Bird
0
0

Consider this simplified handler chain code snippet:

medium📝 Analysis Q13 of 15
LLD - Behavioral Design Patterns — Part 1
Consider this simplified handler chain code snippet:
class Handler:
    def __init__(self, successor=None):
        self.successor = successor
    def handle(self, request):
        if self.can_handle(request):
            return f"Handled {request}"
        elif self.successor:
            return self.successor.handle(request)
        else:
            return "Not handled"
    def can_handle(self, request):
        return False

class ConcreteHandlerA(Handler):
    def can_handle(self, request):
        return request == 'A'

class ConcreteHandlerB(Handler):
    def can_handle(self, request):
        return request == 'B'

chain = ConcreteHandlerA(ConcreteHandlerB())
print(chain.handle('B'))

What is the output of this code?
AHandled B
BHandled A
CNot handled
DError
Step-by-Step Solution
Solution:
  1. Step 1: Trace the request through the chain

    The request 'B' is first checked by ConcreteHandlerA, which returns False for can_handle('B'). It passes the request to ConcreteHandlerB.
  2. Step 2: ConcreteHandlerB handles the request

    ConcreteHandlerB's can_handle('B') returns True, so it returns "Handled B".
  3. Final Answer:

    Handled B -> Option A
  4. Quick Check:

    Request 'B' handled by second handler [OK]
Quick Trick: Request passes chain until a handler returns true [OK]
Common Mistakes:
MISTAKES
  • Assuming first handler handles all requests
  • Confusing return values
  • Missing the chain passing logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes