Course contentsShow
← Java
Lesson 1670 of 2,87035. Functional InterfacesFree lesson

Suppliers for Factory Patterns

Using Supplier to create object factories that produce new instances on demand.

Suppliers for Factory Patterns

You'll learn how to use Supplier<T> to implement the Factory design pattern for on-demand object creation.

The Core Idea

A factory is a design pattern that centralizes object creation logic. Instead of calling new directly everywhere in your code, you delegate creation to a factory. Since Supplier<T> returns a new value each time you call get(), it's a perfect fit for factories that need to produce fresh instances on demand.

Think of a Supplier as a vending machine: each time you press the button (call get()), it dispenses a new product.

How Suppliers Act as Factories

Traditional factory methods often look like this:

Product createProduct() {
    return new Product();
}

With Supplier, you can pass around factory logic as a first-class object:

Supplier<Product> productFactory = () -> new Product();
Product p1 = productFactory.get(); // New instance
Product p2 = productFactory.get(); // Another new instance

Real-World Example

Supplier<StringBuilder> stringBuilderFactory = StringBuilder::new;
Supplier<ArrayList<String>> listFactory = ArrayList::new;

// Create fresh instances whenever needed
StringBuilder sb1 = stringBuilderFactory.get();
StringBuilder sb2 = stringBuilderFactory.get(); // Different object

ArrayList<String> list1 = listFactory.get();
ArrayList<String> list2 = listFactory.get(); // Different list

Why This Matters

Passing Supplier instances gives you flexibility: the caller decides when to create objects, while the supplier encapsulates how they're created. You can swap factories without changing calling code, making testing and configuration easier.

Key Takeaway: Use Supplier<T> as a factory to decouple object creation from usage—each get() call produces a fresh instance, giving you a clean, functional approach to the Factory pattern.