Junior — Middle
Can you give an example of using a behavioral pattern in software design?
sobes.tech AI
Answer from AI
Behavioral design patterns describe ways objects interact and responsibilities are distributed.
Example: the "Strategy" pattern.
It allows defining a family of algorithms, encapsulating each one, and making them interchangeable. This helps change the behavior of an object at runtime without modifying its code.
Example in Java:
// Strategy interface
interface PaymentStrategy {
void pay(int amount);
}
// Concrete strategies
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Credit card payment: " + amount);
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("PayPal payment: " + amount);
}
}
// Context
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
// Usage
ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(1000);
cart.setPaymentStrategy(new PayPalPayment());
cart.checkout(2000);