The strategy design pattern

It is quite a common thing in enterprise applications to have different implementations of specific algorithms and choosing one to use while the application is running. Some examples might include different sorting algorithms that would have a different performance for different sizes or types of data, different parsers for various possible representations of data, and so on.

The strategy design pattern enables us to define a family of algorithms and select a specific one at runtime.

The strategy design pattern helps with encapsulation as each algorithm can be separately defined and then injected into the classes that use it. The different implementations are also interchangeable.

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.