Discover how to implement and apply Strategy design patterns to create flexible, maintainable software solutions.
The Strategy Pattern enables selecting algorithms at runtime by encapsulating related operations into interchangeable components. It allows dynamic switching between payment methods, sorting algorithms, or authentication strategies without altering core business logic.
// PaymentStrategy interface
class PaymentStrategy {
constructor() {
this.type = 'base';
}
pay(amount) {
throw new Error('This method must be implemented');
}
}
class CreditCard extends PaymentStrategy {
constructor(cardNumber) {
super();
this.cardNumber = cardNumber;
}
pay(amount) {
return `Processed $${amount} via credit card ending in ***${this.cardNumber.slice(-4)}`;
}
}
class PayPal extends PaymentStrategy {
constructor(email) {
super();
this.email = email;
}
pay(amount) {
return `Processed $${amount} via PayPal for ${this.email}`;
}
}