Published in


Strategy design pattern — Java

Strategy design pattern tutorial

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


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




A humble place to learn Java and Programming better.

Recommended from Medium

What is Software Development ?

How observability impacts your developer velocity?

Writeup: Mime CTF | ZH

Designing Developer Friendly REST API Products

Potato Bot —Dev Blog #1

I think you’re going to see a lot of that.

Java Serverless on Steroids with fn+GraalVM Hands-On

Boost Your Web App’s Performance

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Passionate java developer who want to share.

More from Medium


How to implement Visitor Design Pattern using Java?

Java OOPS Concepts

Equals() Method Vs “==” Operator in Java