Design Patterns. Strategy Pattern in Examples

Let’s take a look at some Strategy patter examples
Most of the time you will see some pattern definition, explanations, conditions, pitfalls, etc, and only after that — an example. I would like to break this chain and to show you some simplest concrete examples first, and after that — some theory.
UML

📝 If you are not familiar with the term aggregation
you can check more here:
… or you can just take o look at the examples, and you will get the main idea behind it 😉
All examples will be in Typescript, but don’t worry, you will get the main idea.
Example 1
Run:

Result:
ConcreteStrategy_A
ConcreteStrategy_B
Example 2
Result:
6
0
Example 3
In this case, you can add as many types with strategies as you want (very nice implementation of “Open Closed Principle”)
Example 4
Some theory
I don’t think that you will need this, but still… 😉
After those examples, let’s see a few definitions of 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.
- Refactoring guru
Strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
- Wikipedia
Concepts
- Eliminate conditional statements
- Behavior encapsulated in a class
- Difficult to add new strategies
If you would like to know more, you can check here: