Bird
0
0

Given the following code snippet implementing the Payment Strategy Pattern, what will be the output?

medium📝 Analysis Q13 of 15
LLD - Design — Online Shopping Cart
Given the following code snippet implementing the Payment Strategy Pattern, what will be the output?
class PaymentStrategy {
  pay(amount) { throw 'Not implemented'; }
}

class CreditCardPayment extends PaymentStrategy {
  pay(amount) { return `Paid ${amount} with Credit Card`; }
}

class PayPalPayment extends PaymentStrategy {
  pay(amount) { return `Paid ${amount} with PayPal`; }
}

class PaymentContext {
  constructor(strategy) { this.strategy = strategy; }
  executePayment(amount) { return this.strategy.pay(amount); }
}

const context = new PaymentContext(new PayPalPayment());
console.log(context.executePayment(100));
APaid 100 with Credit Card
BNot implemented
CPaid 100 with PayPal
DError: strategy.pay is not a function
Step-by-Step Solution
Solution:
  1. Step 1: Trace the object creation and method calls

    The PaymentContext is created with a PayPalPayment strategy. Calling executePayment(100) calls PayPalPayment's pay method.
  2. Step 2: Understand the pay method output

    PayPalPayment's pay returns 'Paid 100 with PayPal'. This string is printed.
  3. Final Answer:

    Paid 100 with PayPal -> Option C
  4. Quick Check:

    Context uses PayPalPayment = Output with PayPal [OK]
Quick Trick: Check which strategy instance is passed to context [OK]
Common Mistakes:
  • Assuming default or CreditCardPayment is used
  • Expecting an error from base class
  • Confusing method override behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes