DEV Community

Erwan Le Tutour
Erwan Le Tutour

Posted on

Strategy design pattern — Java

design-pattern

Definition of the Strategy pattern

In computer programming, the strategy pattern **(also known as the **policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

Where to use the Factory pattern

When you want the algorithm to vary independently from clients that use it.

UML example

Implementation of the strategy pattern

First, we need to declare an Interface or an Abstract class, here I used both but a single abstract class could have done the job.


what i want to achieve is that depending of the context my code will behave differently so let’s implement some strategy.

For the purpose of this tutorial, i created 2 strategies : PlusOperationStrategy and MinusOperationStrategy, both extending my abstract class.


With them being of the same supertype by inheritance, I can substitute them in the function of the needed behavior.

So now, if I want to use my strategies, and more precisely the compute method implemented in it, I need a context.


So based on the strategy passed as a parameter the context will use the compute method it.

So now, let’s see how it work


The above snippet will return this result
5
-1
Enter fullscreen mode Exit fullscreen mode

Thanks for your reading time, the code used in this tutorial is findable in this Github repository.

Top comments (0)