170. Implementing the Strategy pattern

The classic Strategy pattern is pretty straightforward. It consists of an interface that represents a family of algorithms (strategies) and several implementations of this interface (each implementation is a strategy).

For example, the following interface unifies the strategies for removing characters from the given string:

public interface RemoveStrategy {
String execute(String s);
}

First, we will define a strategy for removing numeric values from a string:

public class NumberRemover implements RemoveStrategy {
@Override
public String execute(String s) {
return s.replaceAll("\d", "");
}
}

Then, we will define a strategy for removing white spaces from a string:

public class WhitespacesRemover implements RemoveStrategy {
@Override
public String execute(String s) {
return s.replaceAll("\s", "");
}
}

Finally, let's define a utility class that acts as the entry point for strategies:

public final class Remover {

private Remover() {
throw new AssertionError("Cannot be instantiated");
}

public static String remove(String s, RemoveStrategy strategy) {
return strategy.execute(s);
}
}

This is a simple and classical Strategy pattern implementation. If we want to remove numeric values from a string, we can do this as follows:

String text = "This is a text from 20 April 2050";
String noNr = Remover.remove(text, new NumberRemover());

But do we actually need the NumberRemover and WhitespacesRemover classes? Do we need to write similar classes for further strategies? Obviously, the answer is no.

Check out our interface one more time:

@FunctionalInterface
public interface RemoveStrategy {
String execute(String s);
}

We've just added the @FunctionalInterface hint because the RemoveStrategy interface defines a single abstract method, and so it is a functional interface.

What can we use in the context of a functional interface? Well, the obvious answer is lambdas. Moreover, what can a lambda do for us in this scenario? It can remove the boilerplate code (in this case, the classes representing the strategies) and encapsulate the strategy in its body:

String noNr = Remover.remove(text, s -> s.replaceAll("\d", ""));
String noWs = Remover.remove(text, s -> s.replaceAll("\s", ""));

So, this is what the Strategy pattern looks like via lambdas.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.144.228