Bird
Raised Fist0

Given the following code snippet, what will be printed when executing the last two lines?

easy🧾 Code Trace Q12 of Q15
OOP & Design Patterns - Strategy Pattern - Replace Conditionals with Polymorphism
Given the following code snippet, what will be printed when executing the last two lines?
from abc import ABC, abstractmethod

class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class CreditCardStrategy(PaymentStrategy):
    def pay(self, amount):
        print(f"Processing credit card payment of ${amount}")

class UPIStrategy(PaymentStrategy):
    def pay(self, amount):
        print(f"Processing UPI payment of ${amount}")

class PaymentStrategyFactory:
    @staticmethod
    def get_strategy(method):
        if method == 'CreditCard':
            return CreditCardStrategy()
        elif method == 'UPI':
            return UPIStrategy()
        else:
            raise ValueError('Invalid payment method')

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

    def pay(self, amount):
        self.strategy.pay(amount)

processor = PaymentProcessor(PaymentStrategyFactory.get_strategy('UPI'))
processor.pay(100)
ARaises ValueError: Invalid payment method
BProcessing credit card payment of $100
CProcessing net banking payment of $100
DProcessing UPI payment of $100
Step-by-Step Solution
  1. Step 1: Trace strategy selection

    The factory method get_strategy('UPI') returns an instance of UPIStrategy.
  2. Step 2: Trace payment method call

    The pay method of UPIStrategy prints "Processing UPI payment of $100".
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct strategy instance leads to correct output [OK]
Quick Trick: Factory returns correct strategy instance for method [OK]
Common Mistakes:
MISTAKES
  • Confusing strategy returned or output string
Trap Explanation:
PITFALL
  • Confusing the strategy returned leads to wrong output guess.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to trace polymorphic calls and factory usage.
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