Bird
0
0

What will be the output of this Python code using Strategy pattern?

medium📝 Analysis Q5 of 15
LLD - Behavioral Design Patterns — Part 1
What will be the output of this Python code using Strategy pattern?
class StrategyA:
def execute(self):
print('Strategy A')
class StrategyB:
def execute(self):
print('Strategy B')
class Context:
def __init__(self, strategy):
self.strategy = strategy
def do_work(self):
self.strategy.execute()
c = Context(StrategyA())
c.strategy = StrategyB()
c.do_work()
AStrategy B
BStrategy A
CError: strategy attribute is read-only
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute reassignment

    Context's strategy attribute is reassigned from StrategyA instance to StrategyB instance before calling do_work().
  2. Step 2: Trace method call

    do_work() calls execute() of current strategy, which is StrategyB, printing "Strategy B".
  3. Final Answer:

    Strategy B -> Option A
  4. Quick Check:

    Reassigned strategy executes new behavior [OK]
Quick Trick: Changing strategy attribute changes behavior at runtime [OK]
Common Mistakes:
MISTAKES
  • Assuming original strategy runs
  • Thinking attribute is immutable
  • Expecting no output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes