What is a design pattern, and what does the strategy pattern give you over an if statement?
A design pattern is a named, reusable solution to a recurring design problem. It is not a piece of code you copy but a structure, a set of collaborating roles and the reasoning about when the structure helps. The classic catalogue groups them into creational, structural and behavioural families.
public class Main {
public static void main(String[] args) {
String text = "Hello World";
System.out.println(new UpperCase().apply(text));
System.out.println(new Reverse().apply(text));
}
}
interface TextFormatter {
String apply(String text);
}
class UpperCase implements TextFormatter {
public String apply(String text) { return text.toUpperCase(); }
}
class Reverse implements TextFormatter {
public String apply(String text) { return new StringBuilder(text).reverse().toString(); }
}The strategy pattern is the simplest one to recognise. Instead of a method that branches on a flag or a type, the varying behaviour is extracted behind a small contract, and the caller is handed one implementation. The output shows the same text formatted two different ways, and the caller never asks which way it wants.
What that buys is extension without modification. A third formatting style is a third class, and nothing that already works is edited. It also makes the variations visible in the code as named types rather than as a chain of conditions.
The honest cost is indirection. A reader now has to find the implementation to know what happens, and every strategy is another class in the codebase. For one conditional with two branches, the pattern is probably overkill. It starts paying when there are several variations, when the order of the branches keeps growing, or when different callers need different variations at the same time.