Bird
0
0

Which of the following is the correct way to define a handler class with a next handler in Python for the Chain of Responsibility pattern?

easy🧠 Conceptual Q3 of 15
LLD - Behavioral Design Patterns — Part 1
Which of the following is the correct way to define a handler class with a next handler in Python for the Chain of Responsibility pattern?
Aclass Handler: def __init__(self, next_handler=None): self.next_handler = next_handler
Bclass Handler: def __init__(self, next_handler): self.next_handler = next_handler def handle(self): pass
Cclass Handler: def __init__(self): self.next_handler = None def set_next(self, handler): self.next_handler = handler
Dclass Handler: def __init__(self): self.next = None def handle(self): pass
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct handler initialization

    class Handler: def __init__(self): self.next_handler = None def set_next(self, handler): self.next_handler = handler shows a handler with a default next_handler set to None and a method to set the next handler, which is a common and clear approach.
  2. Step 2: Compare other options

    class Handler: def __init__(self, next_handler=None): self.next_handler = next_handler lacks a method to set next handler after initialization. class Handler: def __init__(self, next_handler): self.next_handler = next_handler def handle(self): pass requires next_handler at init and lacks flexibility. class Handler: def __init__(self): self.next = None def handle(self): pass uses 'next' instead of 'next_handler' and lacks setter method.
  3. Final Answer:

    class Handler: def __init__(self): self.next_handler = None def set_next(self, handler): self.next_handler = handler -> Option C
  4. Quick Check:

    Handler class with setter method = class Handler: def __init__(self): self.next_handler = None def set_next(self, handler): self.next_handler = handler [OK]
Quick Trick: Use setter method to link handlers flexibly [OK]
Common Mistakes:
MISTAKES
  • Forgetting to initialize next handler
  • Not providing a method to set next handler
  • Using inconsistent attribute names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes