Output
Explanation
Try it Yourself >>
In this example,
PaymentStrategy: Defines a common interface for payment methods.
CreditCardPayment and PayPalPayment: Concrete strategies implementing the payment interface with specific behaviors.
PaymentProcessor: Context class that uses a PaymentStrategy object and can switch strategies dynamically.
Main: Demonstrates switching between different payment strategies at runtime.
27. What are the key components of the Builder Design Pattern?
this.email = email;
}
}
public void processPayment(int amount) {
paymentStrategy.pay(amount);
}
// Context: PaymentProcessor
class PaymentProcessor {
private PaymentStrategy paymentStrategy;
Paying 100 using Credit Card: 1234-5678-9876-5432
Paying 200 using PayPal account:
[email protected]
// Main class
public class Main {
public static void main(String[] args) {
PaymentProcessor processor = new PaymentProcessor();
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
}
@Override
public void pay(int amount) {
System.out.println("Paying " + amount + " using PayPal account: " + email);
}
// Using Credit Card Payment Strategy
PaymentStrategy creditCard = new CreditCardPayment("1234-5678-9876-5432");
processor.setPaymentStrategy(creditCard);
processor.processPayment(100); // Output: Paying 100 using Credit Card: 1234-5678-9876-5432
}
// Switching to PayPal Payment Strategy
PaymentStrategy paypal = new PayPalPayment("
[email protected]");
processor.setPaymentStrategy(paypal);
processor.processPayment(200); // Output: Paying 200 using PayPal account:
[email protected]
}