JAVA-270 · Lesson 3 of 12 · 26 min
Creational patterns
▶ Video coming soon A video version of this lesson is on the way.
Tuesday, January 25, 2028. Ingrid brings a book to the shop: Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, published in 1994. Developers call its authors the Gang of Four. She tells Hamza it is worth knowing but not worth worshipping. The book named 23 patterns that its authors had seen over and over in good object-oriented programs, and gave developers a shared vocabulary: say decorator or strategy to another Java developer and they know what you mean. Some of the patterns matter less in modern Java, because lambdas, records and enums do the same jobs more simply. Tonight's topic is the first group in the book, the creational patterns, which are about how objects get made.
What a design pattern is
A design pattern is a named, reusable solution to a problem that keeps coming up in software design, described in terms of the roles that classes and objects play rather than as finished code. The architect Christopher Alexander introduced the idea for buildings in the 1970s, and the Gang of Four borrowed it. Each pattern in their book has a name, the problem it solves, the structure of the solution and its consequences, including its costs.
Patterns are not things to collect. A pattern is worth using when its problem is your problem. Adding a factory, a builder and a singleton to a program that does not need them makes it harder to read, which is the speculative generality warned about in lesson 1. Ingrid's rule is to reach for a pattern when you feel the pain it removes, and to use its name in comments and conversations so the next reader recognizes it.
| Group | Concerned with | Examples in this course |
|---|---|---|
| Creational | How objects are created | Factory method, abstract factory, builder, singleton |
| Structural | How objects are combined into larger structures | Adapter, decorator, facade, composite, proxy (lesson 4) |
| Behavioral | How objects share responsibilities and communicate | Strategy, observer, command, template method, state, iterator (lesson 5) |
Why creation needs design
Every object starts with new. The trouble with new is that it names one concrete class, so every place that writes new SpreadsheetCatalog() is tied to that class forever. When CounterApp wanted to switch to a different catalog, Hamza had to find and change every new. Creational patterns move the decision about which class to create into one place, so that the rest of the program asks for an object without knowing exactly what it gets.
Factory method
A factory method is a method whose job is to create and return an object, so callers do not use new directly. In its simplest and most common Java form, it is a static method on the type being created, such as List.of, Path.of or Integer.valueOf. A static factory can have a meaningful name, can return a cached object instead of a new one, and can return any subtype of its declared return type, which lets the class change its implementation later without breaking callers.
public class Main {
sealed interface Bike permits CityBike, CargoBike, Tandem {
String name();
int perDayCents();
static Bike of(String type, int number) {
return switch (type) {
case "CITY" -> new CityBike("CITY-" + number);
case "CARGO" -> new CargoBike("CARGO-" + number);
case "TANDEM" -> new Tandem("TANDEM-" + number);
default -> throw new IllegalArgumentException("unknown bike type " + type);
};
}
}
record CityBike(String name) implements Bike { public int perDayCents() { return 2500; } }
record CargoBike(String name) implements Bike { public int perDayCents() { return 4000; } }
record Tandem(String name) implements Bike { public int perDayCents() { return 4500; } }
public static void main(String[] args) {
for (String line : new String[] {"CITY 3", "CARGO 1", "TANDEM 1"}) {
String[] p = line.split(" ");
Bike b = Bike.of(p[0], Integer.parseInt(p[1]));
System.out.println(b.name() + " is a " + b.getClass().getSimpleName() + " at " + b.perDayCents() + " cents a day");
}
}
}CITY-3 is a CityBike at 2500 cents a day CARGO-1 is a CargoBike at 4000 cents a day TANDEM-1 is a Tandem at 4500 cents a day
What this code does
Bike.of reads a type name, such as the ones in the rental file, and returns the right kind of bike, so the code that reads the file never uses new or names a concrete class. If the shop adds an e-bike, only the factory and the new record change. Because Bike is sealed, the compiler knows the complete list of bike types.
The Gang of Four version of factory method is a little different: a parent class declares an abstract method that creates an object, and each subclass overrides it to create its own kind. That form appears less often in modern Java, where passing a lambda or a Supplier that creates the object usually does the same job with less code.
import java.util.*;
import java.util.function.Supplier;
public class Main {
interface Notice { String text(String customer); }
record TextMessage() implements Notice { public String text(String c) { return "SMS to " + c + ": your bike is ready"; } }
record Email() implements Notice { public String text(String c) { return "Email to " + c + ": your bike is ready for pickup"; } }
static final class ReadyNotifier {
private final Supplier<Notice> factory;
ReadyNotifier(Supplier<Notice> factory) { this.factory = factory; }
void notifyAll(List<String> customers) {
for (String c : customers) System.out.println(factory.get().text(c));
}
}
public static void main(String[] args) {
new ReadyNotifier(TextMessage::new).notifyAll(List.of("Ana", "Ben"));
new ReadyNotifier(Email::new).notifyAll(List.of("Cy"));
}
}SMS to Ana: your bike is ready SMS to Ben: your bike is ready Email to Cy: your bike is ready for pickup
What this code does
ReadyNotifier needs to create a notice for each customer but should not decide which kind. It receives a Supplier, a factory written as a constructor reference such as TextMessage::new, and calls get whenever it needs a new notice. Switching every notice from text messages to email means changing the one line that builds the notifier.
Abstract factory
An abstract factory creates whole families of related objects that must be used together. Instead of one factory method, it is an interface with several, one for each member of the family, and each implementation creates a matching set. The classic example is a user interface toolkit with a light theme and a dark theme: a button, a menu and a window from the same theme must match.
At Second Gear the family is the receipt. A paper receipt from the counter printer and an emailed receipt each need a header, a line format and a footer, and mixing a paper header with an email footer would produce nonsense. An abstract factory keeps each family together.
import java.util.*;
public class Main {
interface ReceiptKit {
String header();
String line(String item, int cents);
String footer(int total);
}
static final class PaperKit implements ReceiptKit {
public String header() { return "SECOND GEAR CYCLES 1150 Parsons Ave"; }
public String line(String item, int cents) { return String.format("%-14s %7.2f", item, cents / 100.0); }
public String footer(int total) { return String.format("%-14s %7.2f%nThank you!", "TOTAL", total / 100.0); }
}
static final class EmailKit implements ReceiptKit {
public String header() { return "Your receipt from Second Gear Cycles"; }
public String line(String item, int cents) { return "- " + item + ": " + String.format("%.2f", cents / 100.0); }
public String footer(int total) { return "Total paid: " + String.format("%.2f", total / 100.0); }
}
static void print(ReceiptKit kit, Map<String, Integer> items) {
System.out.println(kit.header());
int total = 0;
for (var e : items.entrySet()) { System.out.println(kit.line(e.getKey(), e.getValue())); total += e.getValue(); }
System.out.println(kit.footer(total));
}
public static void main(String[] args) {
Map<String, Integer> items = new LinkedHashMap<>();
items.put("Tube 700x25", 899);
items.put("Bell", 650);
print(new PaperKit(), items);
System.out.println();
print(new EmailKit(), items);
}
}SECOND GEAR CYCLES 1150 Parsons Ave Tube 700x25 8.99 Bell 6.50 TOTAL 15.49 Thank you! Your receipt from Second Gear Cycles - Tube 700x25: 8.99 - Bell: 6.50 Total paid: 15.49
What this code does
ReceiptKit is an abstract factory for one family of pieces: a header, a line and a footer that belong together. The print method works with any kit, so the same items come out as a paper receipt or an email without print knowing which. Because each kit supplies all three pieces, a paper header can never be paired with an email footer.
Abstract factories are less common than the other creational patterns, and they cost a new interface method in every implementation whenever the family grows. Use one when objects really come in matched sets.
Builder
A builder creates a complex object step by step, collecting the parts and checking them before producing the finished object. It solves two problems. The first is the long constructor: new RepairTicket(611, "Ana", "CITY-2", true, false, null, 3, "brakes") is impossible to read, and easy to get wrong when two arguments have the same type. The second is validation: an object with rules about which combinations are allowed should never exist in an invalid state, and the builder is the natural place to check.
public class Main {
record RepairTicket(int number, String customer, String bike, String kind, boolean rush, String note) {
static Builder builder(int number) { return new Builder(number); }
static final class Builder {
private final int number;
private String customer, bike, kind = "TUNE_UP", note = "";
private boolean rush;
private Builder(int number) { this.number = number; }
Builder customer(String c) { this.customer = c; return this; }
Builder bike(String b) { this.bike = b; return this; }
Builder kind(String k) { this.kind = k; return this; }
Builder rush() { this.rush = true; return this; }
Builder note(String n) { this.note = n; return this; }
RepairTicket build() {
if (customer == null || bike == null) throw new IllegalStateException("customer and bike are required");
if (rush && kind.equals("WHEEL_TRUE")) throw new IllegalStateException("wheel truing cannot be rushed");
return new RepairTicket(number, customer, bike, kind, rush, note);
}
}
}
public static void main(String[] args) {
RepairTicket t = RepairTicket.builder(612).customer("Ana").bike("CITY-2").kind("BRAKES").rush().build();
System.out.println(t);
try {
RepairTicket.builder(613).customer("Ben").bike("CARGO-1").kind("WHEEL_TRUE").rush().build();
} catch (IllegalStateException e) {
System.out.println("refused: " + e.getMessage());
}
}
}RepairTicket[number=612, customer=Ana, bike=CITY-2, kind=BRAKES, rush=true, note=] refused: wheel truing cannot be rushed
What this code does
Each builder method sets one named part and returns the builder, so calls chain into a readable sentence. build checks the shop's rules, here that a customer and bike are given and that wheel truing is never rushed, before creating the record. The finished ticket is an immutable record, so once built it can never become invalid.
Joshua Bloch's book Effective Java recommends a builder whenever a constructor would need more than a handful of parameters, especially optional ones. Records give you a short canonical constructor for free; when a record has many optional components, a nested builder like this one is the usual way to keep creating it readable.
Singleton, and why to be careful
A singleton is a class that has exactly one instance, with a global way to reach it. The Gang of Four included it, and it is the pattern most often misused. A singleton is a global variable with a class around it: any code anywhere can reach it, which hides dependencies, couples distant parts of the program, and makes testing hard, because a test cannot replace the one instance with a fake.
When something really must be unique for the life of the program, Bloch recommends an enum singleton, an enum with a single constant. The Java language guarantees there is exactly one instance, even with serialization and reflection, and it needs no locking. But the usual better answer is not to reach for the singleton from inside other classes at all. Create one instance at start-up and pass it to whoever needs it.
import java.time.*;
public class Main {
enum ShopHours {
INSTANCE;
private final LocalTime open = LocalTime.of(10, 0), close = LocalTime.of(18, 0);
boolean isOpen(LocalTime t) { return !t.isBefore(open) && t.isBefore(close); }
}
static final class HardToTest {
String status() { return ShopHours.INSTANCE.isOpen(LocalTime.now()) ? "open" : "closed"; }
}
static final class EasyToTest {
private final ShopHours hours;
private final Clock clock;
EasyToTest(ShopHours hours, Clock clock) { this.hours = hours; this.clock = clock; }
String status() { return hours.isOpen(LocalTime.now(clock)) ? "open" : "closed"; }
}
public static void main(String[] args) {
ZoneId zone = ZoneId.of("America/New_York");
Clock morning = Clock.fixed(Instant.parse("2028-01-25T14:30:00Z"), zone);
Clock evening = Clock.fixed(Instant.parse("2028-01-25T23:45:00Z"), zone);
System.out.println("same instance: " + (ShopHours.INSTANCE == ShopHours.valueOf("INSTANCE")));
System.out.println("9:30 am: " + new EasyToTest(ShopHours.INSTANCE, morning).status());
System.out.println("6:45 pm: " + new EasyToTest(ShopHours.INSTANCE, evening).status());
}
}same instance: true 9:30 am: closed 6:45 pm: closed
What this code does
ShopHours is an enum singleton, so Java guarantees a single instance. HardToTest reaches for it and for the real clock directly, so its answer depends on when you run it, while EasyToTest receives both the hours and a Clock through its constructor. Fixed clocks make the result the same on every run, which is why the program prints open for 9:30 am and closed for 6:45 pm.
java.time.Clock in that example is a good model of how the standard library handles something that seems global. The current time is the same for everyone, yet Clock is an ordinary object you pass in, with a system version for production and a fixed version for tests. Most things that tempt you toward a singleton, such as configuration, a price list or a connection pool, are better handled the same way.
Dependency injection by constructor
The creational idea with the biggest effect on everyday code is not in the Gang of Four book at all. Dependency injection means a class receives the objects it depends on from outside, usually as constructor parameters stored in final fields, instead of creating or looking them up itself. The class states its needs in its constructor; something else decides what to supply.
That something else is called the composition root: one place, usually near main, where the program creates its real objects and wires them together. Everything else in the program just receives what it needs. Frameworks such as Spring, which Hamza meets in his web services course, automate the wiring for large programs, but the idea works perfectly well by hand.
import java.util.*;
public class Main {
interface PriceList { int cents(String code); }
interface Stock { int count(String code); }
record Quote(String code, int qty, int cents, boolean inStock) {}
static final class QuoteService {
private final PriceList prices;
private final Stock stock;
QuoteService(PriceList prices, Stock stock) { this.prices = Objects.requireNonNull(prices); this.stock = Objects.requireNonNull(stock); }
Quote quote(String code, int qty) {
return new Quote(code, qty, prices.cents(code) * qty, stock.count(code) >= qty);
}
}
public static void main(String[] args) {
Map<String, Integer> priceTable = Map.of("TUBE-700x25", 899, "BELL", 650);
Map<String, Integer> counts = Map.of("TUBE-700x25", 14, "BELL", 1);
PriceList prices = code -> priceTable.getOrDefault(code, 0);
Stock stock = code -> counts.getOrDefault(code, 0);
QuoteService quotes = new QuoteService(prices, stock);
System.out.println(quotes.quote("TUBE-700x25", 3));
System.out.println(quotes.quote("BELL", 2));
}
}Quote[code=TUBE-700x25, qty=3, cents=2697, inStock=true] Quote[code=BELL, qty=2, cents=1300, inStock=false]
What this code does
QuoteService lists what it needs, a price list and a stock count, as constructor parameters and checks that neither is null. main is the composition root: it decides that today both come from small in-memory tables and wires them in. In the real counter program the same service could receive a spreadsheet-backed stock count without any change to its code.
Constructor injection has a pleasant side effect: a class with too many constructor parameters is advertising that it has too many responsibilities. If QuoteService one day needs eight collaborators, the constructor itself is a warning to apply the single responsibility principle.
Choosing a creational pattern
| Problem | Pattern | Modern Java form |
|---|---|---|
| Callers should not name the concrete class | Factory method | A static factory such as Bike.of, or a Supplier |
| Objects come in families that must match | Abstract factory | An interface with one creation method per family member |
| Many optional parts, rules about combinations | Builder | A nested static Builder that validates in build |
| Exactly one instance for the whole program | Singleton | An enum, created once and passed in rather than looked up |
| A class needs collaborators it should not choose | Dependency injection | Constructor parameters stored in final fields, wired in main |
Try it yourself
Build a rental with a builder
The starter has a Rental record and a Builder with bike and days. Add a customer step, and make build throw IllegalStateException("days must be 1 to 14") when days is outside 1 to 14. Then create a 3-day rental of CARGO-1 for Ana, and try a 20-day rental, printing the error message.
The program should print Rental[customer=Ana, bike=CARGO-1, days=3] and then refused: days must be 1 to 14.
public class Main {
record Rental(String customer, String bike, int days) {
static final class Builder {
private String customer = "unknown", bike;
private int days = 1;
Builder bike(String b) { bike = b; return this; }
Builder days(int d) { days = d; return this; }
Rental build() { return new Rental(customer, bike, days); }
}
}
public static void main(String[] args) {
System.out.println(new Rental.Builder().bike("CARGO-1").days(3).build());
System.out.println(new Rental.Builder().bike("CITY-1").days(20).build());
}
}Try it yourself
A static factory for parts
Add a static factory method Part.parse(String line) to the Part record that splits a line like BELL;650 on the semicolon and returns a Part. Use it in main instead of the hand-written splitting, and keep the output the same.
The program should print BELL costs 650 and CHAIN-11 costs 3999.
public class Main {
record Part(String code, int cents) {}
public static void main(String[] args) {
for (String line : new String[] {"BELL;650", "CHAIN-11;3999"}) {
String[] f = line.split(";");
Part p = new Part(f[0], Integer.parseInt(f[1]));
System.out.println(p.code() + " costs " + p.cents);
}
System.out.println("parsed by hand");
}
}Common mistakes
MistakeCollecting patterns because they are famous.
InsteadUse a pattern when you have the problem it solves, and name it so readers recognize it.
MistakeCalling new on concrete classes throughout the program.
InsteadCreate objects in factories or in one composition root, and let other code ask for interfaces.
MistakeConstructors with long lists of same-typed parameters.
InsteadUse a builder with named steps and validation in build.
MistakeReaching for a singleton from inside other classes.
InsteadCreate the single instance once and pass it in through constructors.
MistakeReading the system clock directly in business code.
InsteadInject a java.time.Clock so tests can use a fixed time.
Summary and key terms
- A design pattern is a named, reusable solution to a recurring design problem; the Gang of Four book of 1994 named 23 of them in three groups.
- Creational patterns move the decision about which class to create into one place.
- A factory method, often a static factory such as Bike.of or a Supplier, creates objects so callers do not name concrete classes.
- An abstract factory creates families of related objects that must be used together.
- A builder assembles a complex object step by step and validates it before building.
- A singleton has exactly one instance; the enum form is safest, but passing the single instance in is better than looking it up globally.
- Dependency injection gives a class its collaborators through its constructor, and a composition root near main wires the real objects together. java.time.Clock shows how to inject something that seems global.
- Design pattern
- A named, reusable solution to a problem that recurs in software design.
- Gang of Four
- Gamma, Helm, Johnson and Vlissides, authors of the 1994 book Design Patterns.
- Creational pattern
- A pattern about how objects are created.
- Factory method
- A method that creates and returns an object so callers do not use new on a concrete class.
- Static factory
- A static method that returns an instance of its class or a subtype, such as List.of.
- Abstract factory
- An interface for creating families of related objects that belong together.
- Builder
- An object that collects the parts of a complex object step by step and then builds it.
- Fluent interface
- Methods that return this so calls can be chained into a readable sentence.
- Singleton
- A class with exactly one instance and a global way to reach it.
- Enum singleton
- A singleton written as an enum with a single constant, guaranteed unique by Java.
- Dependency injection
- Supplying a class's collaborators from outside, usually through its constructor.
- Composition root
- The one place, near main, where a program creates and wires its real objects.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Name two advantages of a static factory over a public constructor.
Show answer
It can have a meaningful name, return a cached object or return any subtype.
When is an abstract factory worth its cost?
Show answer
When objects come in families that must match, such as the parts of one receipt format.
What two problems does a builder solve?
Show answer
Unreadable long constructors and objects that could otherwise be created in an invalid state.
Why is a singleton hard to test?
Show answer
Code reaches it globally, so a test cannot swap in a fake; passing it in avoids that.
What is the composition root?
Show answer
The single place near main where real objects are created and wired together.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.