Strategy Pattern in Functional Java

Jose Figueredo
2 min readDec 8, 2020

Strategy is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside original context object.

The original object, called context, holds a reference to a strategy object and delegates it executing the behavior. In order to change the way the context performs its work, other objects may replace the currently linked strategy object with another one.

Traditional approach

Let’s use as example a simple problem: we need to remove certain stuff from a string but we can use different ways to accomplish that. So the behavior is how the algorithm solves the problem.

RemoveStrategy: An abstraction of the algorithm. This is an interface having the abstract operation.

Remover class: A context class that doesn’t know how the concrete RemoveStrategy class is implemented but executes it and returns its results.

A concrete strategy that implements the algorithm.

In this case it removes white spaces in an imperative way using a for loop and comparing with an if statement.

Another concrete strategy that also removes white spaces but in a functional way using stream and filter.

Runner for the example:

The Functional Java way

We will modify from the previous example the RemoveStrategy interface adding the annotation @FunctionalInterface which is used to ensure an interface can only have one abstract method.

An example of an inline function of type RemoveStrategy will be

The functional interface RemoveStrategy is in fact identically to the functional interface UnaryOperator so the example could be rewritten as follows

Or we can simply write the anonymous lambda to shorten even more the example

Conclusion

Perhaps you are used to use the last form of anonymous lambda but not all of you knows where it came from. The other implementations are best suited for more complex algorithms that are several lines long or that delegates behavior to another functions or classes and turns unreadable inside an anonymous lambda.

--

--

Jose Figueredo

Solutions/Cloud Architect. Software developer since forever