Bird
Raised Fist0

In a system with many element classes, how does the Visitor pattern facilitate adding a new operation without modifying existing element classes?

hard📝 Trade-off Q8 of Q15
LLD - Behavioral Design Patterns — Part 2
In a system with many element classes, how does the Visitor pattern facilitate adding a new operation without modifying existing element classes?
ABy creating a new Visitor class implementing the operation and passing it to elements.
BBy adding new methods directly to each element class.
CBy using inheritance to extend element classes with new operations.
DBy embedding operation logic inside element constructors.
Step-by-Step Solution
Solution:
  1. Step 1: Understand Visitor pattern usage

    Visitor pattern allows adding operations by defining new visitor classes.
  2. Step 2: Avoid modifying elements

    Elements remain unchanged; new operations are added via visitors.
  3. Step 3: Implementation

    Create a new Visitor class with the operation and pass it to elements' accept methods.
  4. Final Answer:

    By creating a new Visitor class implementing the operation and passing it to elements. -> Option A
  5. Quick Check:

    New visitors add operations without element changes [OK]
Quick Trick: New Visitor classes add operations without element edits [OK]
Common Mistakes:
MISTAKES
  • Modifying element classes directly
  • Using inheritance instead of visitors
  • Embedding logic inside elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes