Design Patterns In TypeScript — Strategy
How to isolate different variants of an algorithm within an object using the Strategy Pattern
--
The Strategy Pattern is a popular design pattern used to organize as well as and encapsulate algorithms. This pattern is used when is necessary to isolate the business logic of a class from algorithm implementation details that may not be as important in the context of that logic.
What is Strategy?
The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software define the Strategy Pattern as follows:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
The Strategy pattern is to be used where we want to choose the algorithm for each client or to change the behavior at runtime. It should be used to separate and encapsulate anything that changes frequently, enabling all the code that changes stays in one place. Doing this will ensure that the changing code has no effect on the rest of the program, thus making our application more flexible and robust.
How To Implement
The Strategy pattern is usually implemented by creating an abstract class (our Strategy class), as well as its concrete implementations. Each implementation contains an algorithm that supports some behavior of the context class object. The context class will delegate the work to a specific strategy algorithm rather than executing it on its own.
Each client first decides which strategy algorithm context it should use. Next, the client will instantiate the strategy to be used in this context. Then the client uses this strategy to instance a context object. After which the client can decide whether to modify the behavior by calling a method on the context class that overrides the strategy at runtime or to leave it as is.