Design Patterns. Strategy Pattern in Examples

Image for post
Image for post

UML

Image for post
Image for post

All examples will be in Typescript, but don’t worry, you will get the main idea.

Example 1

Run:

Image for post
Image for post

Result:

ConcreteStrategy_A
ConcreteStrategy_B

Example 2

6
0

Example 3

Example 4

Some theory

I don’t think that you will need this, but still… 😉

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

  1. Eliminate conditional statements
  2. Behavior encapsulated in a class
  3. Difficult to add new strategies

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer