Strategy and factory
What you will learn
A strategy packages a replaceable policy, while a factory centralizes construction or selection. They solve different problems: a strategy decides how work is done; a factory decides which object to create. Compose them when a real variation justifies both.
- Replace repeated pricing branches with interchangeable strategies.
- Distinguish a simple factory from Factory Method and Builder.
- Select structural patterns by the problem they solve.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. All examples in this chapter are standalone, single-threaded Java 21 models unless stated otherwise.
Compare branching with composed strategies
public class Main { interface Delivery { int fee(int quantity); } static int before(String kind, int n) { return switch (kind) { case "pickup" -> 0; case "courier" -> n == 0 ? 0 : 500; default -> throw new IllegalArgumentException("kind"); }; } static Delivery choose(String kind) { return switch (kind) { case "pickup" -> n -> 0; case "courier" -> n -> n == 0 ? 0 : 500; default -> throw new IllegalArgumentException("kind"); }; } public static void main(String[] args) { for (String kind : java.util.List.of("pickup", "courier")) { for (int n : new int[]{0, 2}) { int old = before(kind, n); int result = choose(kind).fee(n); if (old != result) throw new AssertionError(); System.out.println(kind + ": " + result); } } }}Expected output:
pickup: 0pickup: 0courier: 0courier: 500The factory is a simple selector, not GoF Factory Method. Quantities here are nonnegative by caller contract. Compare both policies before deciding whether a strategy object is worthwhile.
Creational choices
A simple factory selects an object in one place. GoF Factory Method delegates construction to a subclass or overriding creator; Abstract Factory groups related products. Builder is helpful for validated staged construction or many optional values; Prototype copies an existing configuration, with explicit copy depth. Singleton constrains instance count in a given scope, but global access couples tests and clients; container-managed lifecycle or explicit ownership often fits better.
Structural choices
Adapter translates an incompatible interface; Facade offers a simpler entry point to a subsystem; Decorator wraps an operation to add behavior while keeping its contract; Proxy stands in for a target to control access or lifecycle. Composite treats leaf and group nodes uniformly, and Bridge separates two axes that vary independently. Flyweight shares intrinsic immutable state when measured allocation costs justify it. These are different intents even when implementations look like wrappers.
Strategy versus switch
A small switch is fine for a stable closed set. Extract strategies when independently changing rules, multiple callers or testable policy boundaries justify the extra abstraction. A factory may still use a switch; removing all conditionals is not a goal.
Adapter and decorator at a boundary
public class Main { interface Price { int cents(String sku); } static class Legacy { int centsFor(String code) { if (!code.equals("PEN")) throw new IllegalArgumentException("unknown"); return 250; } } public static void main(String[] args) { Legacy legacy = new Legacy(); Price adapted = sku -> legacy.centsFor(sku.toUpperCase(java.util.Locale.ROOT)); Price audited = sku -> { int cents = adapted.cents(sku); System.out.println("quoted " + sku); return cents; }; System.out.println(audited.cents("pen")); }}Expected output:
quoted pen250The adapter changes the vocabulary from lowercase SKU to the legacy uppercase code. The decorator adds a synthetic audit message without changing the price. Real audit logging must address sensitive data and failure behavior.
Composite: totals for nested bundles
public class Main { interface Item { int cents(); } record Unit(int cents) implements Item { Unit { if (cents < 0) throw new IllegalArgumentException("price"); } } record Group(java.util.List<Item> children) implements Item { Group { children = java.util.List.copyOf(children); } public int cents() { int sum = 0; for (Item item : children) sum = Math.addExact(sum,item.cents()); return sum; } } public static void main(String[] args) { Item bundle = new Group(java.util.List.of(new Unit(200), new Group(java.util.List.of(new Unit(300), new Unit(100))))); System.out.println(bundle.cents()); }}Expected output:
600A group and a leaf implement the same read contract. The tree is small and trusted; a production graph would need depth, cycle and size constraints. The list snapshot is shallow.
Common mistakes
Do not label every static constructor a GoF Factory Method. Avoid a factory that grows into a service locator. Do not wrap a target solely to give the wrapper a pattern name. The purpose determines the pattern, not the number of classes.
Practice
Implement pickup and express delivery policies, chosen by a simple factory. Pickup costs zero, express costs 700 cents for a positive quantity and zero for an empty order. Reject unknown modes and negative quantities.
Expected output:
007000rejectedCompare with the manual review criteria.
Further reading: Patterns. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strategy and factory — knowledge check
Design and domain modeling reasoning.
What does Strategy vary?
Is a static switch returning implementations always GoF Factory Method?
Which wrapper changes the interface expected by a client?
Which pattern treats nested bundles and individual items uniformly?
When is a switch preferable?