# Factory Method Design Pattern — Java Example **Pattern:** Creational → Factory Method **Article:** https://ankurm.com/factory-method-design-pattern-java/ ## What this example shows A notification system where the "send" logic decides which channel object to create, instead of the client doing it with a switch statement. `Notification` is the product interface; `EmailNotification`, `SmsNotification`, and `PushNotification` are concrete products. `NotificationSender` declares the factory method and a template `send()` step shared by every channel; `EmailSender`, `SmsSender`, and `PushSender` each override the factory method to produce their own notification type. `NotificationService` is shown separately as the anti-pattern this pattern replaces — it is not called by `Main`. `Main` demonstrates the cost of adding a new channel (Slack) by adding one new product and one new creator, with zero changes to existing classes. ## How to run ```bash javac factory-method/*.java -d out/factory-method java -cp out/factory-method factorymethod.Main ``` Requires Java 25. ## Post Section ↔ File Mapping | Post Section | File(s) | |---|---| | The Problem: Object Creation Leaks Into Business Logic | `NotificationService.java` (anti-pattern shown for contrast — not called by `Main`) | | Part 1 — The Notification Interface | `Notification.java` | | Part 2 — The Concrete Notification Classes | `EmailNotification.java`, `SmsNotification.java`, `PushNotification.java` | | Part 3 — The NotificationSender Class | `NotificationSender.java` | | Part 4 — The Concrete Sender Subclasses | `EmailSender.java`, `SmsSender.java`, `PushSender.java` | | Part 5 — Running It: Client Code and Output | `Main.java` | | Adding a New Channel (Slack) | `SlackNotification.java`, `SlackSender.java` | Article: https://ankurm.com/factory-method-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/