Strategy

Strategy

Behavioral pattern

The strategy design pattern allows us to set the behavior of a class at runtime. Strategy bases on polymorphism for implementing a series of behaviors that can be interchanged during the execution of the program, allowing for a modification of an object’s behavior by following a strategy that has been set.

Strategy design pattern structure.
Strategy design pattern structure.

The components included in this pattern are:

  • Context: This component encapsulates the strategy to be used, which can be set at runtime.
  • IStrategy: Common interface all strategies must implement. In it, all the operations the strategies need to implement are defined.
  • ConcreteStrategy: It represents the concrete strategies, which inherit from IStrategy.
Strategy design pattern sequence diagram.
Strategy design pattern sequence diagram.
  1. The client creates a new context and sets the StrategyA.
  2. The client executes the doSomethingoperation.
  3. Context hands over this responsibility to ConcreteStrategyA.
  4. ConcreteStrategyA performs the operation and returns the result.
  5. Context takes this result and hands it over to the client.
  6. The client changes the Context strategy at runtime.
  7. The client executes the doSomethingoperation again.
  8. Context hands over this responsibility to ConcreteStrategyB.
  9. ConcreteStategyB performs the operation and returns the result.
  10. Context takes this result and hands it over to the client.

Real-world example

By implementing the Strategy design pattern, we are going to develop an application that offers different authentication methods. User authentication will be achieved via XML file, database or settings file in memory. With the Strategy pattern, the user will be able to establish the preferred authentication method in the application, without having to add any more code.

Discover how the Strategy pattern can help us solve this problem.
Discover how the Strategy pattern can help us solve this problem.

About this book

Introducción a la arquitectura de software

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©