Bird
Raised Fist0

Which modification best preserves the pattern's structure and flexibility?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Template Method Pattern - Define Skeleton, Override Steps
Suppose you want to extend the Template Method Pattern to allow clients to optionally skip multiple steps dynamically at runtime (not just condiments). Which modification best preserves the pattern's structure and flexibility?
AOverride the entire template method in each subclass to conditionally skip steps as needed.
BAdd multiple hook methods in the base class for each optional step, with default implementations returning True or False.
CRemove the base class and implement each beverage's recipe independently with duplicated code.
DUse a flag parameter in prepare_recipe to decide which steps to execute, breaking encapsulation.
Step-by-Step Solution
  1. Step 1: Understand requirement

    Need to optionally skip multiple steps dynamically while preserving fixed sequence and reuse.
  2. Step 2: Evaluate options

    Adding multiple hook methods in base class allows subclasses to override selectively without breaking skeleton.
  3. Step 3: Reject other options

    Overriding entire template method duplicates code and breaks pattern; flags break encapsulation; removing base class loses reuse.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Multiple hooks preserve flexibility and structure [OK]
Quick Trick: Use hooks for optional steps, not override template method [OK]
Common Mistakes:
MISTAKES
  • Overriding template method to skip steps
  • Using flags breaking encapsulation
Trap Explanation:
PITFALL
  • Overriding template method seems flexible but breaks reuse and consistency.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to extend pattern correctly for optional behavior.
Master "Template Method Pattern - Define Skeleton, Override Steps" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes