Strategy Pattern
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows a client to choose which algorithm to use at runtime.
When to Use:
Use the Strategy pattern when you have multiple algorithms for a specific task and you want to choose the appropriate algorithm at runtime.
Example
// PaymentStrategy Interfaceinterface PaymentStrategy { pay(amount: number): void;}
// Concrete Strategiesclass CreditCardPayment implements PaymentStrategy { pay(amount: number): void { console.log(`Paid ${amount} using Credit Card`); }}
class PayPalPayment implements PaymentStrategy { pay(amount: number): void { console.log(`Paid ${amount} using PayPal`); }}
// Contextclass PaymentProcessor { private strategy: PaymentStrategy;
constructor(strategy: PaymentStrategy) { this.strategy = strategy; }
setStrategy(strategy: PaymentStrategy) { this.strategy = strategy; }
processPayment(amount: number) { this.strategy.pay(amount); }}
// Usageconst processor = new PaymentProcessor(new CreditCardPayment());processor.processPayment(100);
processor.setStrategy(new PayPalPayment());processor.processPayment(150);Pros:
- Promotes Open/Closed Principle.
- Easy to switch between different algorithms.
Cons:
- Increases the number of classes in the application.
- Clients must be aware of different strategies.