Design Pattern | Strategy Pattern

What Is the Strategy Pattern?

  • Strategy means strategy. In programming, it is often easier to understand as an algorithm.
  • Programs are written to solve problems. To solve a problem, a specific algorithm is implemented. The Strategy pattern is a way to quietly replace the part that implements the algorithm.
  • It allows a system to be changed and extended flexibly.
  • It lets the user(Client) choose a suitable Strategy and execute logic with it.
  • In GoF design patterns, it is classified as a behavioral design pattern.

Example Program

The example is a rock-paper-scissors program. It includes a strategy that chooses a hand randomly and a strategy that only chooses rock.

Class Diagram
Strategy Pattern Class Diagram

The example defines a Hand class for rock-paper-scissors hands, a Strategy interface for choosing hands and learning from results, concrete strategies, and a player class that delegates hand selection to its strategy.

Advantages

Algorithms can be replaced without changing the client. Related algorithms can be encapsulated behind a common interface, making it easy to add new strategies or switch behavior at runtime.