Lesson 2 of 6
Creational Patterns - Singleton, Factory, Builder
Creational patterns deal with object creation - when, how, and by whom objects are created. They decouple the code that creates objects from the code that uses them. Singleton, Factory Method, Abstract Factory, and Builder are the most commonly used.
Singleton, Factory Method & Builder
// ─── Singleton ──────────────────────────────────────────────
// One instance throughout the application lifetime.
// ✅ Thread-safe with initialization-on-demand holder idiom
public class AppConfig {
private AppConfig() { /* private - no external instantiation */ }
private static class Holder {
static final AppConfig INSTANCE = new AppConfig(); // created only when Holder is loaded
}
public static AppConfig getInstance() { return Holder.INSTANCE; }
// ✅ Or with enum (serialisation-safe, reflection-safe)
public enum DbPool {
INSTANCE;
private final List<Connection> pool = new ArrayList<>();
public Connection getConnection() { /* */ return pool.isEmpty() ? null : pool.remove(0); }
}
// ─── Factory Method ─────────────────────────────────────────
// Delegate creation to subclasses - decouple object creation from use.
interface Notification { void send(String message, String recipient); }
class EmailNotification implements Notification {
public void send(String message, String recipient) {
System.out.printf("📧 Email to %s: %s%n", recipient, message);
}
}
class SmsNotification implements Notification {
public void send(String message, String recipient) {
System.out.printf("📱 SMS to %s: %s%n", recipient, message);
}
}
class PushNotification implements Notification {
public void send(String message, String recipient) {
System.out.printf("🔔 Push to %s: %s%n", recipient, message);
}
}
// Factory - creation logic in ONE place; callers just say what type they want
class NotificationFactory {
public static Notification create(String type) {
return switch (type.toUpperCase()) {
case "EMAIL" -> new EmailNotification();
case "SMS" -> new SmsNotification();
case "PUSH" -> new PushNotification();
default -> throw new IllegalArgumentException("Unknown notification type: " + type);
};
}
// Static factory methods - useful on the class itself
// Book.ofIsbn(isbn), Book.fromCsv(line)
}
// ─── Builder ─────────────────────────────────────────────────
// Construct complex objects step by step; telescoping constructor anti-pattern eliminated.
public class BookOrder {
private final String isbn;
private final int quantity;
private final double unitPrice;
private final String memberId;
private final boolean priority;
private final String notes;
// With 6+ params, constructors become unreadable: new BookOrder("001", 2, 39.99, "MBR1", true, null)
// Builder - readable, flexible, immutable result
private BookOrder(Builder b) {
this.isbn = b.isbn;
this.quantity = b.quantity;
this.unitPrice = b.unitPrice;
this.memberId = b.memberId;
this.priority = b.priority;
this.notes = b.notes;
}
public static class Builder {
private final String isbn; // required
private final int quantity; // required
private double unitPrice;
private String memberId;
private boolean priority = false;
private String notes;
public Builder(String isbn, int quantity) {
this.isbn = Objects.requireNonNull(isbn);
if (quantity < 1) throw new IllegalArgumentException("quantity >= 1");
this.quantity = quantity;
}
public Builder unitPrice(double p) { this.unitPrice = p; return this; }
public Builder memberId(String m) { this.memberId = m; return this; }
public Builder priority() { this.priority = true; return this; }
public Builder notes(String n) { this.notes = n; return this; }
public BookOrder build() { return new BookOrder(this); }
}
}
// Usage - reads like a sentence:
BookOrder order = new BookOrder.Builder("ISBN-001", 2)
.unitPrice(39.99)
.memberId("MBR-001")
.priority()
.notes("Gift wrap requested")
.build();Quick Quiz
Tip
Tip
Practice Creational Patterns Singleton Factory Builder in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Creational Patterns - Singleton, Factory, Builder
Practice Task
Note
Practice Task - (1) Write a working example of Creational Patterns Singleton Factory Builder from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Creational Patterns Singleton Factory Builder is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?