Bird
0
0

Given the following code snippet using the Strategy pattern, what will be the output?

medium📝 Analysis Q13 of 15
LLD - Behavioral Design Patterns — Part 1
Given the following code snippet using the Strategy pattern, what will be the output?
class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def execute(self):
        return self.strategy.do_action()

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

class StrategyB:
    def do_action(self):
        return 'Action B'

context = Context(StrategyB())
print(context.execute())
AAction B
BAction A
CError: StrategyB has no method do_action
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Trace object creation and method calls

    The Context is created with StrategyB() instance. Calling context.execute() calls StrategyB.do_action().
  2. Step 2: Check StrategyB.do_action() return value

    StrategyB.do_action() returns the string 'Action B', so print(context.execute()) outputs 'Action B'.
  3. Final Answer:

    Action B -> Option A
  4. Quick Check:

    Context with StrategyB = 'Action B' output [OK]
Quick Trick: Context calls strategy's method, output matches chosen strategy [OK]
Common Mistakes:
MISTAKES
  • Assuming default strategy is StrategyA
  • Thinking method do_action is missing
  • Confusing class and instance usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes