Java design patterns — Builder, Strategy, and Observer
Builder pattern, method chaining, immutable objects, Strategy pattern, interchangeable algorithms, Observer pattern, event listeners, open-closed principle, separation of concerns
Essential Design Patterns
Design patterns are reusable solutions to recurring design problems. Three patterns appear constantly in Java codebases.
Builder — Complex Object Construction
public class HttpRequest {
private final String url;
private final String method;
private final int timeout;
private HttpRequest(Builder b) {
this.url = b.url; this.method = b.method; this.timeout = b.timeout;
}
public static class Builder {
private String url, method = "GET";
private int timeout = 30;
public Builder url(String url) { this.url = url; return this; }
public Builder method(String m) { this.method = m; return this; }
public Builder timeout(int t) { this.timeout = t; return this; }
public HttpRequest build() { return new HttpRequest(this); }
}
}
HttpRequest req = new HttpRequest.Builder()
.url("https://api.example.com")
.method("POST")
.timeout(60)
.build();
Strategy — Swappable Algorithms
interface SortStrategy { void sort(int[] arr); }
class Sorter {
private SortStrategy strategy;
public Sorter(SortStrategy s) { this.strategy = s; }
public void setStrategy(SortStrategy s) { this.strategy = s; }
public void sort(int[] arr) { strategy.sort(arr); }
}
Sorter sorter = new Sorter(Arrays::sort);
sorter.sort(new int[]{3,1,2}); // uses Arrays.sort
Observer is implemented natively in Java through event listeners and property change support. Builder solves telescoping constructors. Strategy replaces conditionals that select algorithms.
All three patterns enforce the open-closed principle: code is open for extension but closed for modification. Adding a new sort algorithm to a Strategy-based Sorter requires no changes to the Sorter class itself. Adding a new Observer requires no changes to the Subject. This is the primary reason these patterns appear throughout mature Java codebases.
