The Strategy Pattern
The Strategy Pattern is a behavioral software design pattern.
It enables selecting an algorithm at runtime instead of hardcoding only one possible solution.
We’ll take a look at what it actually is and how it can help you to write better software.
The issue
Whenever you hard-code some very specific logic, without the ability to replace it on-demand, you’re tying yourself to that specific logic.
No way to replace it, except changing code. And sometimes changing code is not what you want to do, at all.
An object-oriented example
Imagine a class which is responsible to handle the creation of reports. In this particular case, you want to send reports out and have hard-coded an algorithm to send them over to a printer.
class ReportService {
createReportAndSend() {
// ...
// ...
const result = sendReport(report); if (result.error != null) {
throw new Error("Sending report failed");
}
}
sendReport(report: Report): ReportSendResult {
const printerAddress = getPrinterAddress();
const serializedReport = serializeReport(report);
return sendReportToPrinter(serializedReport);
}
}