Strategy
Definition
The strategy pattern enables selecting an algorithm at runtime. Instead of hardcoding behavior into a class, you extract it into separate strategy classes that all follow the same interface. This makes it easy to swap algorithms without changing the code that uses them.
Implementation
Let’s say we have a payment controller (our context) that must support different payment methods. Instead of hardcoding the different payment methods into the payment controller, we can use the strategy pattern to delegate the payment processing to seperate strategy implementations.
This also allows us to easily add new payment methods in the future without changing the payment controller.
class PaymentController(private val processor: PaymentProcessor) {
fun pay(amount: Double) {
processor.process(amount)
}
}The strategy interface defines the contract for the different payment methods:
interface PaymentProcessor {
fun process(amount: Double)
}The concrete strategy implementations are the different payment methods:
object CreditCardPaymentProcessor : PaymentProcessor {
override fun process(amount: Double) {
println("Processing credit card payment of $amount")
}
}
object PayPalPaymentProcessor : PaymentProcessor {
override fun process(amount: Double) {
println("Processing PayPal payment of $amount")
}
}