For the complete documentation index, see llms.txt. This page is also available as Markdown.

Strategy Design Pattern

lets the algorithm vary independently from clients that use it

When to use it?

  • When you want to define a class that will have one behavior that is similar to other behavior in the list.

  • When you need to use one of the several behaviors dynamically

Pros ( πŸ‘) & Cons ( πŸ‘Ž)

  • πŸ‘ Often reduces the long list of conditionals

  • πŸ‘ Reduce duplicate code

  • πŸ‘ Keeps class changes from forcing other class changes

  • πŸ‘ can hide complicated/secret code from the user

  • πŸ‘You can replace inheritance with composition.

  • πŸ‘Ž Increased number of objects and classes

  • πŸ‘ŽA lot of modern programming languages have functional-type support that lets you implement different versions of an algorithm inside a set of anonymous functions. Then you could use these functions exactly as you’d have used the strategy objects, but without bloating your code with extra classes and interfaces.

----

The Strategy pattern can be implemented with a simple anonymous (lambda) function in most modern programming languages.

Code

Strategy Design Pattern

References

Last updated