Skip to content
Ameen Abozaid
In reviewJNR-005-L02

Factory

  • Lesson 2 of 10
  • 10 min read
  • Junior
On This Lesson 4 topics

The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.

In this lesson

hide how objects are created.

Planned topics

  • Problem: callers should not know which class to create.
  • A factory method returns the right object.
  • Use it when creation has rules or choices.
  • Return an interface or sealed type, not the concrete class.
  • JDK examples: List.of, Optional.of, Calendar.getInstance.
Draft outline details

Demonstration

java
static Discount discountFor(String code) {
    return switch (code) {
        case "SUMMER10" -> new Percentage(10);
        case "WELCOME5" -> new FixedAmount(Money.eur(500));
        default -> throw new IllegalArgumentException(code);
    };
}

Check your understanding

What does a factory hide?

Show answer

Which concrete class is created and how.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.