Factory
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
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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.