Bird
0
0

You have a system with multiple element types and want to add a new operation without modifying existing element classes. How does the Visitor pattern help in this scenario?

hard📝 Trade-off Q15 of 15
LLD - Behavioral Design Patterns — Part 2
You have a system with multiple element types and want to add a new operation without modifying existing element classes. How does the Visitor pattern help in this scenario?
ABy using inheritance to extend element classes with new operations
BBy creating a new visitor class implementing the operation for all element types
CBy adding new methods to each element class directly
DBy storing operations inside element objects as data
Step-by-Step Solution
Solution:
  1. Step 1: Understand the problem of adding new operations

    Modifying existing element classes is risky and breaks encapsulation.
  2. Step 2: Apply Visitor pattern solution

    Create a new visitor class that implements the new operation for all element types, keeping element classes unchanged.
  3. Final Answer:

    By creating a new visitor class implementing the operation for all element types -> Option B
  4. Quick Check:

    Visitor adds operations via new visitor classes [OK]
Quick Trick: Add new visitor class for new operations [OK]
Common Mistakes:
MISTAKES
  • Modifying element classes directly
  • Using inheritance to add operations
  • Embedding operations as data in elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes