What is a design pattern, and what does the strategy pattern give you over an if statement?
A design pattern is a named solution to a problem that comes up again and again. The strategy pattern is the one where you take a piece of behaviour out of a class and put it behind an interface, so that it can be swapped.
public class Main {
public static void main(String[] args) {
String text = "Hello World";
System.out.println(new UpperCase().apply(text));
}
}
And here is the strategy in code. There is an interface and two implementations of it.
public interface TextFormatter {
String apply(String text);
}
public class UpperCase implements TextFormatter {
@Override
public String apply(String text) {
return text.toUpperCase();
}
}
public class TitleCase implements TextFormatter {
@Override
public String apply(String text) {
return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
}
}
And the class that uses it holds a formatter and asks it to do the work.
public class Greeter {
private final TextFormatter formatter;
public Greeter(TextFormatter formatter) {
this.formatter = formatter;
}
public String greet(String name) {
return formatter.apply("Hello, " + name);
}
}
And what does that give you over an if statement? Here is the version with the if statement.
public class Greeter {
private final String mode;
public Greeter(String mode) {
this.mode = mode;
}
public String greet(String name) {
String text = "Hello, " + name;
if (mode.equals("upper")) {
return text.toUpperCase();
} else if (mode.equals("title")) {
return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
}
return text;
}
}
And here is what the strategy buys you.
the thing the if statement the strategy
------------------------ ------------------------ ------------------------
a new way to format add a branch and a add a class, and nothing
string to compare else changes
the code that reads it the reader has to know the reader can see the
every mode list of the formatters
testing you need a mode for each you give a fake
test
the size it grows with the modes it stays the same
And there is one more thing that is worth knowing about, and it is that the strategy also removes the string. The if version compares strings that the caller has to spell exactly right, so a typo in the mode is a bug that only shows up at run time. With the strategy there is no string at all.
And the last thing is about the deciding. So when you have one behaviour and several ways of doing it then the strategy is right. And when the behaviour is chosen once and never changes then you may not need it.
So the rule to remember is this. The strategy turns a branch into a class, and a new class is easier to add than a new branch.
The next two questions in this topic are about why patterns exist and about when to avoid them.