00:00

Creational Design Patterns in Java

Last updated:

Creational design patterns in Java are proven ways to control how objects are created, so that the rest of the code does not depend on concrete classes, long constructors or expensive setup. Instead of calling new everywhere, you hand creation to a factory, a builder, a single shared instance or a copyable template.

They matter because creation code spreads quickly. Every new SmtpConnection(...) inside business logic ties that logic to one class, repeats configuration, and may open an expensive resource again and again. Creational patterns put those decisions in one place. They are one of the three Gang of Four (GoF) categories, together with structural and behavioral patterns.

1. What Are Creational Design Patterns?

The GoF book describes creational patterns as patterns that abstract the instantiation process, making a system independent of how its objects are created, composed and represented.

In everyday terms, they answer: who creates this object, when, and with what configuration? The answer is moved out of the code that uses the object. A client asks a factory for "a sender for SMS" and receives an interface; it asks a builder for a message and receives a validated, immutable object; it asks for "the connection pool" and always gets the same instance.

Two ideas run through the category. Patterns such as Factory Method and Abstract Factory hide which concrete class is instantiated, so clients depend on interfaces. Patterns such as Builder, Singleton and Prototype control how and how often an instance is made. Both reduce coupling and keep the "new" keyword out of business logic, which supports the Dependency Inversion and Single Responsibility principles.

2. The 5 Creational Patterns at a Glance

PatternIn one sentenceTypical Java example
SingletonExactly one instance, with a single point of access.Runtime.getRuntime(), enum singletons
Factory MethodLet a method or subclass decide which class to instantiate.Collection.iterator(), Calendar.getInstance()
Abstract FactoryCreate families of related objects that must match.java.sql.Connection creating statements
BuilderAssemble a complex object step by step, then build().HttpRequest.newBuilder(), StringBuilder-style APIs
PrototypeCreate new objects by copying a configured instance.Copy constructors, clone()

A Simple Factory, a class with one create(type) method, is not one of the 23 GoF patterns, but it is the most common factory in real code. Object Pool and Dependency Injection are often discussed alongside this category too. Each pattern above has a full tutorial on JavaByTechie with three runnable examples.

3. When Are Creational Patterns Useful?

  • The class to create depends on data: an email or SMS sender chosen by the customer's preference.
  • Objects are complex or must be valid: messages, payment requests or shipments with many optional fields.
  • Creation is expensive: connection pools, rate tables or compiled templates that should be built once and shared or copied.

4. UML Class Diagram

A whole category has no single diagram, so this one shows four creational patterns working together in the notification code from section 8.

Creational patterns in one notification service SenderFactory creates EmailSender or SmsSender, which implement Sender and use the ConnectionPool singleton. Message.Builder creates Message, and Message.copyFor creates copies of a configured message. Factory SenderFactory + forChannel(channel): Sender returns «interface» Sender + send(message): String EmailSender SmsSender Singleton «enum» ConnectionPool INSTANCE + connection(channel) uses Builder Message.Builder + subject(), body(), priority() + build(): Message «create» Message + builder(to): Builder + copyFor(to): Message Prototype (copyFor) sent by
Four creational patterns in one notification service: a factory chooses the sender, a singleton owns the connections, a builder makes messages, and copyFor() copies a configured message.
  1. Factory: SenderFactory returns a Sender; only the factory names EmailSender and SmsSender.
  2. Singleton: both senders use ConnectionPool.INSTANCE, an enum with exactly one constant.
  3. Builder: Message.Builder collects the fields and creates the immutable Message (underlined builder() is static).
  4. Prototype: copyFor() creates a new message from an existing, configured one.

5. Step-by-Step Execution Flow

  1. The client calls Message.builder("asha@..."), sets the subject and body, and calls build(), which validates and returns an immutable message.
  2. It calls SenderFactory.forChannel(EMAIL) and receives a Sender.
  3. send() touches ConnectionPool.INSTANCE for the first time, so the JVM initialises the enum and the pool starts, exactly once.
  4. The client calls shipped.copyFor("ravi@...") to reuse the same content for another recipient, and sends it through the same pool.
  5. For SMS, the factory returns an SmsSender, which reuses the already-started pool.

6. Real-World Use Cases

  • E-commerce: factories for shipping and tax calculators, builders for orders and search queries, prototypes for product variants.
  • Payments and banking: per-gateway factories, regional abstract factories for tax and currency rules, builders for payment requests, and pre-configured offer templates copied per customer.
  • Notifications: channel factories, message builders and shared, expensive clients.
  • The JDK: Integer.valueOf() and List.of() (static factory methods), HttpClient.newBuilder() and HttpRequest.newBuilder() (Builder, Java 11+), Runtime.getRuntime() (Singleton) and ArrayList.clone() (Prototype, shallow).
  • Spring: the IoC container is a BeanFactory; @Bean methods are factory methods; beans are singleton-scoped by default, meaning one instance per application context; Spring Boot offers builders such as RestClient.builder() and WebClient.builder().

7. Problem Without Creational Patterns

Notification code that creates everything with new, inside the business method:

NotificationsWithoutCreationalPatterns.java
public class NotificationsWithoutCreationalPatterns {

    // An expensive resource that should exist once
    static final class SmtpConnection {
        SmtpConnection(String host) { System.out.println("  opening SMTP connection to " + host); }
    }

    // A message with a long constructor: which String is which?
    static final class Message {
        final String to, subject, body;
        final boolean urgent;

        Message(String to, String subject, String body, boolean urgent) {
            this.to = to;
            this.subject = subject;
            this.body = body;
            this.urgent = urgent;
        }
    }

    // Business code creates everything itself, with new, on every call
    static String notifyCustomer(String channel, Message message) {
        if (channel.equals("EMAIL")) {
            new SmtpConnection("smtp.example.com");               // a new connection per message
            return "email to " + message.to + ": " + message.subject;
        } else if (channel.equals("SMS")) {
            return "sms to " + message.to + ": " + message.body;
        }
        throw new IllegalArgumentException("Unknown channel " + channel);
    }

    public static void main(String[] args) {
        System.out.println(notifyCustomer("EMAIL", new Message("asha@example.com", "Order shipped", "Your order is on the way", false)));
        System.out.println(notifyCustomer("EMAIL", new Message("ravi@example.com", "Your order is on the way", "Order shipped", false)));   // swapped arguments
        System.out.println(notifyCustomer("SMS", new Message("+91-98xxxxxx10", "Order shipped", "Your order is on the way", true)));
    }
}
Console
  opening SMTP connection to smtp.example.com
email to asha@example.com: Order shipped
  opening SMTP connection to smtp.example.com
email to ravi@example.com: Your order is on the way
sms to +91-98xxxxxx10: Your order is on the way
  • Repeated expensive work: a new SMTP connection for every email.
  • Error-prone construction: two String arguments were swapped, so Ravi's subject is the body text.
  • Tight coupling: the business method knows every channel class and how to set it up.
  • Duplication: the same message is rebuilt by hand for every recipient.

8. Creational Design Patterns in Java: The Solution

Give each creation problem its own pattern: a Singleton for the shared connection pool, a Factory for choosing the sender, a Builder for messages, and a Prototype-style copy for reusing a configured message.

CreationalPatternsTogether.java
public class CreationalPatternsTogether {

    // Singleton: one shared connection pool, created on first use (enum: thread-safe and serialization-safe)
    enum ConnectionPool {
        INSTANCE;

        ConnectionPool() { System.out.println("  connection pool started"); }

        String connection(Channel channel) { return channel == Channel.EMAIL ? "smtp-conn-1" : "sms-gateway-conn-1"; }
    }

    enum Channel { EMAIL, SMS }

    enum Priority { NORMAL, URGENT }

    // Builder + Prototype: readable construction, and copies of a configured template
    static final class Message {
        private final String to;
        private final String subject;
        private final String body;
        private final Priority priority;

        private Message(Builder b) {
            this.to = b.to;
            this.subject = b.subject;
            this.body = b.body;
            this.priority = b.priority;
        }

        static Builder builder(String to) { return new Builder(to); }

        Message copyFor(String recipient) {                      // prototype-style copy of a ready template
            return new Builder(recipient).subject(subject).body(body).priority(priority).build();
        }

        static final class Builder {
            private final String to;
            private String subject = "";
            private String body = "";
            private Priority priority = Priority.NORMAL;

            private Builder(String to) { this.to = to; }

            Builder subject(String value) { subject = value; return this; }
            Builder body(String value) { body = value; return this; }
            Builder priority(Priority value) { priority = value; return this; }

            Message build() {
                if (body.isBlank()) throw new IllegalStateException("message body is required");
                return new Message(this);
            }
        }
    }

    // Product interface and concrete products
    interface Sender { String send(Message message); }

    static final class EmailSender implements Sender {
        public String send(Message m) {
            return "email to " + m.to + " via " + ConnectionPool.INSTANCE.connection(Channel.EMAIL) + ": " + m.subject;
        }
    }

    static final class SmsSender implements Sender {
        public String send(Message m) {
            return "sms to " + m.to + " via " + ConnectionPool.INSTANCE.connection(Channel.SMS)
                    + ": " + m.body + (m.priority == Priority.URGENT ? " [urgent]" : "");
        }
    }

    // Factory: the only place that knows which class serves which channel
    static final class SenderFactory {
        private SenderFactory() { }

        static Sender forChannel(Channel channel) {
            return switch (channel) {
                case EMAIL -> new EmailSender();
                case SMS -> new SmsSender();
            };
        }
    }

    public static void main(String[] args) {
        Message shipped = Message.builder("asha@example.com")
                .subject("Order shipped")
                .body("Your order is on the way")
                .build();

        Sender email = SenderFactory.forChannel(Channel.EMAIL);
        System.out.println(email.send(shipped));
        System.out.println(email.send(shipped.copyFor("ravi@example.com")));     // same content, new recipient

        Message urgent = Message.builder("+91-98xxxxxx10").body("Your order is on the way").priority(Priority.URGENT).build();
        System.out.println(SenderFactory.forChannel(Channel.SMS).send(urgent));
    }
}
Console
  connection pool started
email to asha@example.com via smtp-conn-1: Order shipped
email to ravi@example.com via smtp-conn-1: Order shipped
sms to +91-98xxxxxx10 via sms-gateway-conn-1: Your order is on the way [urgent]

The pool starts once and is shared. Named builder methods make the subject/body swap impossible, and build() rejects a message without a body. Business code no longer names any sender class, and copying the configured message removes the hand-written duplication. The program runs on Java 21 with java CreationalPatternsTogether.java.

9. Best Practices and Common Mistakes

Best practices

  • Return interfaces from factories, and keep constructors of products private or package-private where possible.
  • Prefer an enum or the holder idiom for singletons, and inject them rather than calling getInstance() everywhere.
  • Make built products immutable and validate in build().
  • Thread safety: lazy creation must be safe under concurrency (class initialisation, volatile double-checked locking or computeIfAbsent); builders are not thread-safe and should stay on one thread.

Common mistakes

  • Singletons as global variables, holding mutable request data.
  • Shallow copies in prototypes that share mutable lists.
  • Factories for one class that will never have a second implementation.
  • Re-implementing what Spring already does, such as hand-written singletons for beans the container manages.

10. When to Use and When Not to Use

Use them when object creation involves choices, configuration, validation or cost that callers should not repeat, or when you want to swap implementations through configuration or for tests.

Avoid them for simple value objects and records with a few required fields, where a constructor or static factory method is clearer. Inside a Spring Boot application, prefer letting the container create and wire beans before writing your own factories and singletons.

11. Advantages and Disadvantages

Advantages

  • Loose coupling: clients depend on interfaces, not concrete classes.
  • One place for creation logic and configuration.
  • Valid, readable construction through builders.
  • Control over cost through sharing (Singleton) and copying (Prototype).

Disadvantages

  • More classes and indirection.
  • Hidden global state if singletons are misused.
  • Overhead for simple objects that a constructor handles well.

12. Comparison of the Creational Patterns

PatternSolvesVariesChoose it when
SingletonToo many instances of a shared resourceNothing: one instanceA resource must be unique per process
Factory MethodHard-coded concrete classesWhich class is createdThe type depends on data or a subclass
Abstract FactoryMismatched related objectsWhich family is createdSeveral products must match each other
BuilderLong, unreadable constructorsHow one object is assembledMany optional settings or cross-field validation
PrototypeCostly or repeated setupWhich configured instance is copiedA ready-made object already holds most of the state

The most common confusions are Factory Method versus Abstract Factory (one product versus a matching family), and Builder versus a factory (how to assemble versus which class to choose). Compared with the other categories, creational patterns deal with making objects; structural patterns deal with combining them, and behavioral patterns with how they interact.

13. Summary

  • Creational design patterns in Java control how, when and how often objects are created.
  • Purpose: remove concrete classes, expensive setup and fragile constructors from business code.
  • The five GoF patterns are Singleton, Factory Method, Abstract Factory, Builder and Prototype.
  • They work by moving creation into factories, builders, shared instances or copyable templates.
  • Used for senders, gateways, regional kits, request objects, connection pools and templates.
  • Benefits: loose coupling, valid objects and controlled cost.
  • Keep singletons stateless, deep-copy mutable fields, and let Spring create beans where it can.

14. Java Design Pattern Interview Questions and Answers

Q1. Why is calling new directly in business code considered a design smell?

new binds the caller to one concrete class and its constructor. Changing the implementation, adding configuration or substituting a test double then requires editing every caller. Creational patterns and dependency injection move that decision to one place.

Q2. Which creational patterns are class-based and which are object-based?

Factory Method is a class creational pattern: it uses inheritance, with subclasses deciding what to create. Abstract Factory, Builder, Prototype and Singleton are object creational patterns: they delegate creation to another object or control instances directly.

Q3. What is the difference between a static factory method and the Factory Method pattern?

A static factory method, as in Effective Java, is a named static method that replaces a constructor, such as List.of() or Integer.valueOf(). The GoF Factory Method is an overridable instance method whose subclasses decide which product to create. Both hide the concrete class; only the GoF version uses inheritance to vary it.

Q4. What are the advantages of static factory methods over constructors?

They have names, so intent is clear (Money.ofRupees(500)). They can return a cached instance instead of a new one, return a subtype, or choose the subtype from the arguments, and they can hide the implementing class. The cost is that classes without public constructors cannot be subclassed.

Q5. Which Singleton implementation would you recommend in Java, and why?

An enum singleton for most cases: the JVM guarantees one instance, thread-safe initialisation, and protection against serialization and reflection attacks. When you need lazy initialisation of a class that cannot be an enum, use the initialisation-on-demand holder idiom.

public enum AuditTrail {
    INSTANCE;
    public void record(String event) { ... }
}
Q6. Is a Spring singleton bean the same as a GoF Singleton?

No. Spring creates one instance per bean definition per application context, and the class keeps a public constructor. The container enforces "one", not the class itself, which is why Spring beans are easy to replace in tests while GoF singletons are not.

Q7. Why is double-checked locking broken without volatile?

Without volatile, the JVM may publish the reference to the new instance before its constructor's writes are visible to other threads, so another thread can see a half-initialised object. Since Java 5 (JSR-133), declaring the field volatile establishes the happens-before ordering that makes the idiom safe.

Q8. When does Builder beat a constructor?

When a class has several parameters of the same type, many optional ones, or rules that span several fields. Named builder methods prevent swapped arguments, defaults remove overloads, and build() can validate everything before an object exists. For two or three required fields, a constructor or record is simpler.

Q9. What is a step builder, and why use it?

A builder that returns a different interface after each required step, so the next method is only available once the previous one is called and build() only after all required steps. Forgetting a required field becomes a compile error instead of a runtime exception.

Q10. What is the difference between a shallow and a deep copy in the Prototype pattern?

A shallow copy duplicates field values, so references to mutable objects such as lists are shared between the original and the copy. A deep copy also duplicates those mutable objects, so changes to the copy cannot affect the original. Object.clone() and ArrayList.clone() are shallow.

Q11. Why do many developers avoid Cloneable?

Cloneable is a marker interface without a clone() method, Object.clone() is protected and throws a checked exception, and it bypasses constructors, which also blocks reassigning final fields in deep copies. Copy constructors or copy() methods are clearer and safer.

Q12. Factory Method or Abstract Factory: how do you decide?

Use Factory Method when one product varies, for example which sender to create. Use Abstract Factory when several products must vary together and stay consistent, such as tax calculator, currency formatter and invoice template for one country.

Q13. How does Spring's IoC container relate to creational patterns?

The container is a large factory: BeanFactory and ApplicationContext create, configure and cache beans. @Bean methods are factory methods, FactoryBean<T> plugs in custom creation logic, the default scope gives one instance per context, and prototype scope creates a new instance per lookup, by calling the constructor, not by copying.

Q14. A factory returns a cached object instead of a new one. Is that still a factory, and is it safe?

Yes. A factory controls creation, so caching is allowed, as Integer.valueOf() and Boolean.valueOf() show. It is safe only when the returned objects are immutable or stateless; mutable objects must be created per caller.

Q15. How do you add a new product type without editing the factory?

Use a registry instead of a switch: implementations register themselves, and the factory looks them up. In plain Java, java.util.ServiceLoader discovers implementations; in Spring, inject a Map<String, Product> of all implementing beans.

ServiceLoader<PaymentGateway> gateways = ServiceLoader.load(PaymentGateway.class);
gateways.forEach(g -> registry.put(g.name(), g));
Q16. Your service runs as five pods. Is a Singleton still unique?

No. A singleton is unique per class loader, which normally means per JVM, so five pods have five instances. Cluster-wide uniqueness needs external coordination, such as a database lock, leader election or a single queue consumer.

Q17. How do you make a lazily created cache entry thread-safe without explicit locks?

Use ConcurrentHashMap.computeIfAbsent(): it runs the creation function at most once per key, while other threads asking for the same key wait for the result. Keep the creation function short, because it runs while that key's entry is locked.

Q18. Why is it risky to call overridable methods from a constructor during object creation?

The superclass constructor runs before the subclass's fields are initialised, so an overridden method called from it sees null or zero values. This often surprises developers who mix Template Method with construction. Call such methods after the object is fully built, for example from a factory.

Q19. How do creational patterns help with unit testing?

When business code receives factories, builders and shared services through its constructor, a test can pass fakes: a factory that returns a stub sender, or an in-memory pool. Code that calls new or a global getInstance() directly is much harder to isolate.

Q20. Records, sealed types and static factories: how have modern Java features changed creational code?

Records give immutable data classes with canonical constructors and compact validation, which reduces the need for builders for small objects. Sealed hierarchies with switch expressions make factory methods exhaustive, so the compiler catches unhandled types. Builders, factories and enum singletons remain the right tools for larger objects, runtime choices and shared resources.