Strategy Method | JavaScript Design Pattern
Last Updated :
08 Nov, 2023
Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the client to choose an algorithm from a family of algorithms at runtime, without altering the code that uses these algorithms.
Important Topics for the Strategy Method Design Pattern in Javascript Design Patterns
Example of Strategy Method in JavaScript Design Patterns
The problem statement is essentially to create a flexible and extensible discount system for a shopping cart, allowing for different discount strategies to be easily added and applied to different shopping carts. This pattern is useful for scenarios where you want to decouple the discount logic from the shopping cart and make it easy to change or extend the discount strategies.
Key Component of Strategy Method:
- Context: This is the class or component that uses the Strategy. It maintains a reference to a Strategy object and can switch between different strategies at runtime.
- Strategy Interface: An interface or an abstract class that defines a set of methods that concrete strategies must implement.
- Concrete Strategies: These are the individual implementations of the Strategy Interface. They encapsulate specific algorithmic behaviors.
Step-by-step Implementation of the above Problem:
Strategy Interface: DiscountStrategy is an abstract class with a method calculateDiscount(orderTotal) that needs to be implemented by concrete discount strategies.
JavaScript
// Strategy Interface
class DiscountStrategy {
calculateDiscount(orderTotal) {
// To be implemented by concrete strategies
}
}
Concrete Strategies: There are three concrete discount strategies implemented in the code:
- NoDiscount: Provides no discount (returns 0).
- TenPercentDiscount: Applies a 10% discount on the order total.
- TwentyPercentDiscount: Applies a 20% discount on the order total.
JavaScript
// Concrete Strategies
class NoDiscount extends DiscountStrategy {
calculateDiscount(orderTotal) {
return 0;
}
}
class TenPercentDiscount extends DiscountStrategy {
calculateDiscount(orderTotal) {
return orderTotal * 0.1;
}
}
class TwentyPercentDiscount extends DiscountStrategy {
calculateDiscount(orderTotal) {
return orderTotal * 0.2;
}
}
Context: The ShoppingCart class represents the shopping cart and takes a discount strategy as a parameter during initialization. It allows items to be added to the cart and calculates the total order price, taking into account the selected discount strategy.
JavaScript
class ShoppingCart {
constructor(discountStrategy) {
this.discountStrategy = discountStrategy;
this.items = [];
}
addItem(item) {
this.items.push(item);
}
calculateTotal() {
const orderTotal = this.items.reduce((total, item) => total + item.price, 0);
return orderTotal - this.discountStrategy.calculateDiscount(orderTotal);
}
}
Example Usage: Three different shopping carts (cart1, cart2, and cart3) are created with different discount strategies and items. The code calculates and prints the total price for each cart after applying the selected discount strategy.
JavaScript
// Example usage
const noDiscount = new NoDiscount();
const tenPercentDiscount = new TenPercentDiscount();
const twentyPercentDiscount = new TwentyPercentDiscount();
const cart1 = new ShoppingCart(noDiscount);
cart1.addItem({ name: 'Item 1', price: 50 });
console.log('Cart 1 Total:', cart1.calculateTotal());
const cart2 = new ShoppingCart(tenPercentDiscount);
cart2.addItem({ name: 'Item 1', price: 50 });
console.log('Cart 2 Total:', cart2.calculateTotal());
const cart3 = new ShoppingCart(twentyPercentDiscount);
cart3.addItem({ name: 'Item 1', price: 50 });
console.log('Cart 3 Total:', cart3.calculateTotal());
Code Implementation of the above Problem:
JavaScript
// Strategy Interface
class DiscountStrategy {
calculateDiscount(orderTotal) {
// To be implemented by concrete strategies
}
}
// Concrete Strategies
class NoDiscount extends DiscountStrategy {
calculateDiscount(orderTotal) {
return 0;
}
}
class TenPercentDiscount extends DiscountStrategy {
calculateDiscount(orderTotal) {
return orderTotal * 0.1;
}
}
class TwentyPercentDiscount extends DiscountStrategy {
calculateDiscount(orderTotal) {
return orderTotal * 0.2;
}
}
// Context
class ShoppingCart {
constructor(discountStrategy) {
this.discountStrategy = discountStrategy;
this.items = [];
}
addItem(item) {
this.items.push(item);
}
calculateTotal() {
const orderTotal = this.items.reduce((total, item) => total + item.price, 0);
return orderTotal - this.discountStrategy.calculateDiscount(orderTotal);
}
}
// Example usage
const noDiscount = new NoDiscount();
const tenPercentDiscount = new TenPercentDiscount();
const twentyPercentDiscount = new TwentyPercentDiscount();
const cart1 = new ShoppingCart(noDiscount);
cart1.addItem({ name: 'Item 1', price: 50 });
console.log('Cart 1 Total:', cart1.calculateTotal());
const cart2 = new ShoppingCart(tenPercentDiscount);
cart2.addItem({ name: 'Item 1', price: 50 });
console.log('Cart 2 Total:', cart2.calculateTotal());
const cart3 = new ShoppingCart(twentyPercentDiscount);
cart3.addItem({ name: 'Item 1', price: 50 });
console.log('Cart 3 Total:', cart3.calculateTotal());
OutputCart 1 Total: 50
Cart 2 Total: 45
Cart 3 Total: 40
Diagrammatic explanation of the Above Example
.jpg)
Lets understand the Diagram
- Context: This represents the class that contains a reference to the Strategy interface. It is responsible for configuring and using the strategies. The "Context" class has a private instance variable called "strategy" that refers to the Strategy interface. It also contains a method "execute()" which delegates the work to the strategy object.
- Strategy: This is an interface or an abstract class that defines the method "algorithm()". It represents the common interface for all supported algorithms. Concrete strategy classes implement this interface.
- ConcreteStrategy1, ConcreteStrategy2, ...: These are the concrete classes that implement the Strategy interface. Each of these concrete classes encapsulates a specific algorithm. For instance, "ConcreteStrategy1" and "ConcreteStrategy2" represent two different algorithms. They both implement the "algorithm()" method defined in the Strategy interface.
The arrows in the diagram illustrate the relationships between the classes.
- The association between "Context" and "Strategy" shows that the "Context" class has a reference to the Strategy interface.
- The arrows pointing from the "Context" to the "ConcreteStrategy" classes indicate that the "Context" can use any of the concrete strategies interchangeably by switching the current strategy.
- The "execute()" method in the "Context" class is the entry point for using the strategies.
Overall, this structure allows the "Context" class to utilize different algorithms without being dependent on their specific implementations. It enables the client to switch between different algorithms easily at runtime, promoting flexibility and maintainability.
Use Cases of Strategy Method in JavaScript Design Patterns
- Algorithm Selection: It allows you to choose an algorithm at runtime, so that system can employ various algorithms interchangeably depending on specific needs. Sorting, searching, and other algorithmic operations frequently use this.
- Behavioral Variations: The Strategy pattern offers a tidy method to encapsulate each algorithm and switch them out as needed when you have a collection of related behaviours or algorithms that must change independently. Applications where various behaviours must be implemented based on specific conditions may find this helpful.
- Complex Decision-making Logic: It helps in avoiding complex conditional statements by encapsulating each condition or decision-making logic into its own strategy. This simplifies the code, making it more maintainable and easier to understand.
- Dynamic Runtime Behavior: The Strategy pattern allows you to change the behavior of an object dynamically at runtime, providing flexibility and adaptability to the system.
Advantages of the Strategy Method in JavaScript Design Patterns
- Flexibility: It allows for easy addition or modification of strategies without altering the client code.
- Isolation: We can isolate the specific implementation details of the algorithms from the client’s code.
- Reusability: Strategies can be reused across different contexts.
- Clean Code: Promotes a clean and modular design by separating the algorithm from the context.
- Maintainability: Encapsulating each algorithm or behavior within its own class, makes it easier to modify, test, and extend the codebase without affecting other parts of the code.
- Easy Testing: With the Strategy pattern, it becomes easier to test individual algorithms independently of the context.
- Run-time Switching: It is possible that application can switch the strategies at the run-time.
Disadvantages of the Strategy Method in JavaScript Design Patterns
- Increased Number of Classes: If there are many strategies, it can lead to a larger number of classes, which can be hard to manage.
- Creating Extra Objects: In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one.
- Awareness among clients: Difference between the strategies should be clear among the clients to able to select a best one for them.
- Complexity: Implementing the Strategy pattern can introduce additional classes and complexity into your code. Each strategy has its own class, and managing these classes can become complex for large systems.
- Increased Code Size: The additional classes and interfaces introduced by the Strategy pattern can lead to an increase in code size.
Conclusion
The Strategy Method is a powerful design pattern that facilitates dynamic algorithm selection at runtime, ensuring code flexibility and reusability. By separating algorithms from clients, it encourages clean, maintainable code that aligns with the Open/Closed Principle. Despite its benefits, it's important to manage the potential complexity and increased class count, which may impact system architecture. Overall, the Strategy Method is valuable for encapsulating various behaviors and enabling algorithm interchangeability without client code modification, making it an effective approach for robust software development.
Similar Reads
JavaScript Design Patterns Tutorial
Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best
8 min read
Creational Software Design Patterns in JavaScript
Builder Method | JavaScript Design Pattern
The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa
9 min read
Prototype Method - JavaScript Design Pattern
A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance
3 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface
6 min read
Behavioural Software Design Patterns in JavaScript
Template Method | JavaScript Design Patterns
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure
10 min read
State Method Design Patterns in JavaScript
State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.
4 min read
Iterator Method | JavaScript Design Pattern
Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi
4 min read
Strategy Method | JavaScript Design Pattern
Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t
8 min read
Observer Method – JavaScript Design Pattern
Observer design pattern, a staple of behavioral design patterns in JavaScript, provides a means to establish a one-to-many relationship between objects. This design pattern is especially valuable for decoupling components and facilitating extensibility in software applications. By employing this pat
10 min read
Command Method | JavaScript Design Patterns
The command method is a behavioral design pattern that encapsulates an incoming request into a standalone object. This object contains all the necessary information to perform a request including the method to call and parameters. Important Topics for the Command Method in JavaScript Design Patterns
6 min read
Visitor Pattern | JavaScript Design Patterns
The visitor pattern is a behavioral design pattern that allows you to add new behaviors or operations to a set of objects without modifying their structure. It achieves this by separating the algorithm from the objects on which it operates. Important Topics for the Visitor Pattern in JavaScript Desi
12 min read
Structural Software Design Patterns in JavaScript
Adapter Method | JavaScript Design Patterns
Adapter Pattern in JavaScript is a structural design pattern that allows you to make one interface or object work with another that has a different interface. It acts as a bridge, enabling the compatibility of two systems that would not naturally work together. Important Topics for the Adapter Metho
8 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation
4 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to ma
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emer
9 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise fro
5 min read
Factory Method in JavaScript | Design Pattern
The Factory Design Pattern is a creational pattern that allows for the creation of objects without exposing the creation logic to the client. It involves creating a separate factory function that is responsible for creating instances of various related objects based on a specified input. In modern s
7 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Fl
4 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite hel
6 min read
Software Design Pattern in other Programming Languages
Python Design Patterns Tutorial
Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
8 min read
Modern C++ Design Patterns Tutorial
Design patterns in C++ help developers create maintainable, flexible, and understandable code. They encapsulate the expertise and experience of seasoned software architects and developers, making it easier for newer programmers to follow established best practices. What are C++ Design Patterns?A des
7 min read