Design patterns
patterns2FactoryMethodPattern
- Path
- pkg8patterns/patterns2FactoryMethodPattern.java
- Package
- pkg8patterns
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg8patterns/patterns2FactoryMethodPattern.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg8patterns;2 3/*4 * Factory Method (Creational)5 * ---------------------------6 * INTENT: define an interface for creating an object, but let subclasses decide7 * which class to instantiate.8 * UML: Creator + factoryMethod(): Product ; ConcreteCreator overrides it.9 * PROS: decouples client from concrete classes; open/closed for new products.10 * CONS: many small subclasses.11 * REAL-WORLD: java.util.Calendar.getInstance, NumberFormat.getInstance.12 */13public class patterns2FactoryMethodPattern {14 15 interface Notification { String send(); }16 static class Email implements Notification { public String send() { return "Email sent"; } }17 static class Sms implements Notification { public String send() { return "SMS sent"; } }18 static class Push implements Notification { public String send() { return "Push sent"; } }19 20 // Factory method centralizes object creation21 static Notification create(String type) {22 return switch (type.toLowerCase()) {23 case "email" -> new Email();24 case "sms" -> new Sms();25 case "push" -> new Push();26 default -> throw new IllegalArgumentException("unknown type: " + type);27 };28 }29 30 public static void main(String[] args) {31 for (String t : new String[]{"email", "sms", "push"}) {32 System.out.println(t + " -> " + create(t).send());33 }34 }35}