Strategy Pattern
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
The Strategy design pattern allows for the creation of a family of algorithms, each encapsulated in a separate class, making them interchangeable. This pattern is useful when a class has multiple ways of performing a task, as it allows for the extraction of these algorithms into separate classes, reducing code bloat and improving maintainability. The context class delegates work to a linked strategy object, abstracting away the specific implementation details.
The Strategy pattern allows for the interchangeable use of different algorithms within an object at runtime. It enables the isolation of algorithm implementation details from the code that uses them. The pattern is useful when there are multiple similar classes that differ only in their execution behavior.
Slides
Step by Step Implementation
Let’s use the Strategy Pattern to create a system that calculates discounts in a shopping cart. Different discount algorithms (e.g., percentage discount, fixed amount discount, or no discount) will act as interchangeable strategies. The steps follow your instructions.
Live Editor function StrategyDemo() { class ShoppingCart { constructor() { this.totalAmount = 0; this.discountAlgorithm = null; // Placeholder for strategy } setDiscountAlgorithm(discountAlgorithm) { this.discountAlgorithm = discountAlgorithm; } calculateTotal() { if (!this.discountAlgorithm) { throw new Error("No discount algorithm set!"); } return this.discountAlgorithm.calculate(this.totalAmount); } addItem(price) { this.totalAmount += price; } } return <div>Step 1: Context class ShoppingCart defined with discount algorithm placeholder.</div>; } Result Loading... |