Strategy pattern is one of the Behaviour Patterns that allow you to define a group of algorithms and behaviours and encapsulate them in a separate class and make them interchangeable without modifying the original code. To put it differently, it’s a contract between the service that you use and the way you want to use it. Usually, it will involve abstracting/changing the implementation of an external service so that it works with your strategy (for example stripe and paypal).

Example

type PaymentStrategy = {  
	pay(amount: number): void;  
};  
  
class CreditCardPayment implements PaymentStrategy {  
	pay(amount: number): void {  
		console.log(`Payd ${amount} using Credit card`);  
	}  
}  
  
class PaypalPayment implements PaymentStrategy {  
	pay(amount: number): void {  
		console.log(`Paid ${amount} using Paypal`);  
	}  
}  
  
class BitcoinPayment implements PaymentStrategy {  
	pay(amount: number): void {  
		console.log(`Paid ${amount} using Bitcoin`);  
	}  
}  
  
export class Payment {  
	private strategy: PaymentStrategy;  
  
	constructor(strategy: PaymentStrategy) {  
		this.strategy = strategy;  
	}  
  
	setStrategy(strategy: PaymentStrategy) {  
		this.strategy = strategy;  
	}  
  
	processPayment(amount: number) {  
		this.strategy.pay(amount);  
	}  
}  
  
const payment = new Payment(new CreditCardPayment());  
  
payment.setStrategy(new PaypalPayment());