Explain the Factory Method pattern.
Topic: design-patterns, Creational Patterns. Level: Basic.
Answer
Factory Method defines an interface for creating an object but lets subclasses (or a factory method) decide **which concrete class** to instantiate. It decouples client code from concrete types — the client depends on an abstraction and asks a factory for an instance, so adding a new product doesn't change client code (Open/Closed). Use it when a class can't anticipate the object type it must create, or to centralize/standardize object creation.
```java
interface Notification { void send(String msg); }
class Email implements Notification { public void send(String m){ /*...*/ } }
class Sms implements Notification { public void send(String m){ /*...*/ } }
class Push implements Notification { public void send(String m){ /*...*/ } }
class NotificationFactory {
static Notification create(String type) { // one place decides the type
return switch (type) {
case "email" -> new Email();
case "sms" -> new Sms();
case "push" -> new Push();
default -> throw new IllegalArgumentException(type);
};
}
}
// Client depends only on the interface:
Notification n = NotificationFactory.create("sms"); n.send("hi");
```