What is the Factory pattern and why is it commonly used?

The Factory pattern is a creational pattern that centralizes object creation behind a method, so the calling code doesn't need to know or specify the exact class being instantiated. This is commonly used to keep object-creation logic in one place and decoupled from the code that uses the objects.

Key Points: • A factory method returns an object based on an interface or abstract type, hiding the concrete class from the caller. • It lets a class defer instantiation decisions to a factory or to subclasses, following the "program to an interface" principle. • New concrete types can be introduced by extending the factory, without changing code that already calls it. • It's useful whenever object creation involves conditional logic, configuration, or varying subtypes based on runtime input. • It keeps construction logic out of business logic, which improves readability and testability.

Example: A NotificationFactory can return an EmailNotification, SmsNotification, or PushNotification object based on a type parameter, so calling code just does Notification n = factory.create(type) without knowing the concrete class.

Code Example:

interface Notification {
    void send(String message);
}

class EmailNotification implements Notification {
    public void send(String message) { System.out.println("Email: " + message); }
}

class NotificationFactory {
    public static Notification create(String type) {
        switch (type) {
            case "EMAIL": return new EmailNotification();
            default: throw new IllegalArgumentException("Unknown type: " + type);
        }
    }
}

Interview Tip: A concise interview answer is:

"Factory centralizes object creation behind a method so callers depend on an interface rather than a concrete class, which is useful whenever creation involves conditional logic or varies by input. It's commonly used because it keeps construction details out of business logic and makes it easy to add new types later without touching existing callers."