What is the Factory pattern?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex OOP Concepts topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
The Factory pattern provides an interface for creating objects without specifying the exact class to be instantiated. It delegates object creation to subclasses or factory methods, enabling loose coupling. Simple Factory (not a GoF pattern but common): class ShapeFactory { public static Shape createShape(String type) { switch (type.toLowerCase()) { case "circle": return new Circle(); case "square": return new Square(); case "triangle": return new Triangle(); default: throw new IllegalArgumentException("Unknown shape: " + type); } } } // Client code: Shape shape = ShapeFactory.createShape("circle"); shape.draw(); // Doesn't know or care which class is instantiated. Factory Method pattern (GoF): define the interface in base class, let subclasses decide which class to instantiate: abstract class Dialog { // Factory method: public abstract Button createButton(); // Template method uses factory method: public void render() { Button btn = createButton(); // Which Button? Decided by subclass btn.onClick(() -> closeDialog()); btn.render(); } } class WindowsDialog extends Dialog { @Override public Button createButton() { return new WindowsButton(); } } class WebDialog extends Dialog { @Override public Button createButton() { return new HTMLButton(); } } // Client: Dialog dialog = new WindowsDialog(); dialog.render(); // Uses WindowsButton without knowing it. Abstract Factory: create families of related objects: interface GUIFactory { Button createButton(); Checkbox createCheckbox(); } class WindowsFactory implements GUIFactory { ... } class MacFactory implements GUIFactory { ... }. Benefits: Single Responsibility (creation in one place), Open/Closed Principle (add new products without changing existing code), loose coupling (client doesn't depend on concrete classes).
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.