The Factory Method pattern defines an interface for creating objects but lets subclasses decide which class to instantiate.

Problem

A class cannot anticipate the exact type of objects it needs to create.

Solution

  public abstract class Dialog {
    public void render() {
        Button button = createButton();
        button.render();
    }

    protected abstract Button createButton(); // factory method
}

public class WindowsDialog extends Dialog {
    @Override
    protected Button createButton() {
        return new WindowsButton();
    }
}

public class MacDialog extends Dialog {
    @Override
    protected Button createButton() {
        return new MacButton();
    }
}
  

Static Factory Method

A common Java idiom — a static method that returns instances:

  public class User {
    public static User createGuest() {
        return new User("guest", Role.GUEST);
    }

    public static User createAdmin(String name) {
        return new User(name, Role.ADMIN);
    }
}
  

Java Standard Library Examples

  List<String> list = List.of("a", "b");           // factory method
Integer value = Integer.valueOf(42);              // valueOf factory
Pattern pattern = Pattern.compile("[a-z]+");      // compile factory
ExecutorService pool = Executors.newFixedThreadPool(4);
  

Factory Method vs Constructor

Factory Method Constructor
Can return subtypes Must return exact type
Can have descriptive names Always new ClassName()
Can cache/reuse instances Always creates new instance
Can return Optional or null Throws on failure

When to Use

  • Exact type of object is determined at runtime
  • Client code should not depend on concrete classes
  • You want descriptive creation methods (createGuest(), fromJson())

Best Practices

  • Name factory methods clearly: of, from, valueOf, create
  • Return interface types, not concrete classes
  • Consider using records with static factory methods for value objects
  • In Spring, @Bean methods in @Configuration classes are factory methods