Bird
Raised Fist0

Consider the following Python code implementing the Strategy Pattern for payment processing:

easy🧾 Trace Q3 of Q15
OOP & Design Patterns - Strategy Pattern - Replace Conditionals with Polymorphism
Consider the following Python code implementing the Strategy Pattern for payment processing:
class PaymentStrategy:
    def pay(self, amount):
        pass

class CreditCardStrategy(PaymentStrategy):
    def pay(self, amount):
        print(f"Paid ${amount} using Credit Card")

class PaymentProcessor:
    def __init__(self, strategy):
        self.strategy = strategy
    def pay(self, amount):
        self.strategy.pay(amount)

processor = PaymentProcessor(CreditCardStrategy())
processor.pay(100)

What will be the output when the last line is executed?
APaid $100 using Credit Card
BPaid 100 using Credit Card
CPaid $100 using UPI
DError: pay method not implemented
Step-by-Step Solution
Solution:
  1. Step 1: Understand the code behavior

    CreditCardStrategy's pay method prints 'Paid $amount using Credit Card'.
  2. Step 2: Trace execution

    Calling processor.pay(100) invokes CreditCardStrategy.pay(100), printing the formatted string.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Verify string formatting and method call correctness [OK]
Quick Trick: Look for method calls and string formatting [OK]
Common Mistakes:
MISTAKES
  • Ignoring the $ sign in the formatted string
  • Confusing strategy class used
  • Assuming abstract method causes error
Trap Explanation:
PITFALL
  • Ignoring string formatting leads to wrong output assumption
Interviewer Note:
CONTEXT
  • Tests ability to trace Strategy Pattern code execution
Master "Strategy Pattern - Replace Conditionals with Polymorphism" 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