Bird
Raised Fist0

Identify the error in the following Strategy pattern implementation:

medium📝 Analysis Q14 of Q15
LLD - Behavioral Design Patterns — Part 1
Identify the error in the following Strategy pattern implementation:
class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def execute(self):
        return self.strategy.action()

class StrategyA:
    def do_action(self):
        return 'Action A'

context = Context(StrategyA())
print(context.execute())
AContext calls a method 'action' which does not exist in StrategyA
BStrategyA class is missing the constructor
CContext should not store strategy as an instance variable
DNo error, code runs correctly
Step-by-Step Solution
Solution:
  1. Step 1: Compare method names between Context and StrategyA

    Context calls self.strategy.action(), but StrategyA defines do_action(), not action().
  2. Step 2: Identify mismatch causing error

    This mismatch causes an AttributeError at runtime because action() is undefined in StrategyA.
  3. Final Answer:

    Context calls a method 'action' which does not exist in StrategyA -> Option A
  4. Quick Check:

    Method name mismatch = runtime error [OK]
Quick Trick: Check method names match between context and strategy [OK]
Common Mistakes:
MISTAKES
  • Ignoring method name mismatch
  • Assuming missing constructor causes error
  • Thinking strategy should not be stored in context

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes