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

Identify the aspects of your application that vary and separate them from what stays the same.

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

References

Last updated