Design Patterns (GoF) (50 Qs)•Part 1: Creational & Structural Patterns (1 - 10)
What is the Strategy Pattern and how does it eliminate `if/else` ladders?
junior LevelCode Exampledesign-patternsCreational
In Simple Words: Defines a family of interchangeable algorithms, encapsulates each one, and makes them interchangeable at runtime:
- Context: Holds a reference to a Strategy interface.
- Client passes the desired strategy dynamically:
typescript
interface CompressionStrategy {
compress(files: string[]): void;
}
class ZipCompression implements CompressionStrategy {
compress(files: string[]) { /* zip logic */ }
}
class RarCompression implements CompressionStrategy {
compress(files: string[]) { /* rar logic */ }
}
class Archiver {
constructor(private strategy: CompressionStrategy) {}
setStrategy(strategy: CompressionStrategy) { this.strategy = strategy; }
createArchive(files: string[]) { this.strategy.compress(files); }
}