Strategy Pattern
Introduction
A client can select an algorithm from a set of algorithms at runtime.
You know that an object can have states and behaviors. And some of these behaviors may vary among the objects of a class. This pattern focuses on the changing behaviors that can be associated with an object at a specific time.
You also have a context object that controls the logic of setting and evaluating the current strategy.
GOF definition
It defines a family of algorithms, encapsulates each one, and makes them interchangeable. The Strategy pattern lets the algorithm vary independently from the clients that use it.
When to use ?
- You have different variants of an algorithm and you want to interchange them at runtime: The variants of the algorithm might try different paths or conditions and you want the application to be able to switch between them based on some criteria. For example, when you want to calculate taxes for an individual, you may apply different strategies based on the individual's marital status, income, or any disabilities they have. You can create different strategies based on their current state.
Real World Examples
- The
nuxt-authcontainsaddAuthorizefunction that accepts different auth strategies based on theOAuthframework.
Implementation
- In the
Strategypattern, you typically have aninterfaceorabstractclass that represents thestrategy, defining a contract for the behavior. Concrete classes implement this interface or extend the abstract class, providing their own implementation for the behavior. The client code holds a reference to the strategy interface and can dynamically set or switch between different concrete strategies as needed.
Example
BillingStrategyis an interface that defines the contract for different billing strategies. It declares acalculatemethod that needs to be implemented by concrete strategy classes.ConcreteBillingStrategyAandConcreteBillingStrategyBare concrete implementations of theBillingStrategyinterface. They provide their own implementations for thecalculatemethod, specific to their respective strategies.BillingContextis the context class that uses the billing strategies. It has a strategy field representing the current billing strategy. The constructor accepts an initial strategy, and thesetStrategymethod allows switching to a different strategy at runtime. ThecalculateBillmethod delegates the billing calculation to the current strategy.