Java Notes
Complete guide to Factory patterns — Simple Factory, Factory Method, and Abstract Factory with UML, Java implementations, and real-world applications.
Intent
Define an interface for creating objects, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
UML Structure — Factory Method
When to Use
- You don't know in advance which class to instantiate
- A class wants its subclasses to specify the objects it creates
- You want to centralize object creation logic
- You need to decouple client code from concrete classes
- Adding new product types should not require modifying existing code (Open/Closed)
Factory Method Pattern
// Product hierarchy
interface Document {
void open();
void save();
String getType();
}
class PDFDocument implements Document {
@Override public void open() { System.out.println("Opening PDF viewer"); }
@Override public void save() { System.out.println("Saving as .pdf"); }
@Override public String getType() { return "PDF"; }
}
class WordDocument implements Document {
@Override public void open() { System.out.println("Opening Word processor"); }
@Override public void save() { System.out.println("Saving as .docx"); }
@Override public String getType() { return "Word"; }
}
class SpreadsheetDocument implements Document {
@Override public void open() { System.out.println("Opening spreadsheet app"); }
@Override public void save() { System.out.println("Saving as .xlsx"); }
@Override public String getType() { return "Spreadsheet"; }
}
// Creator hierarchy
abstract class Application {
// Factory Method — subclasses decide what to create
protected abstract Document createDocument();
// Template method using the factory
public void newDocument() {
Document doc = createDocument();
System.out.println("Created " + doc.getType() + " document");
doc.open();
}
public void saveDocument() {
Document doc = createDocument();
doc.save();
}
}
class PDFApplication extends Application {
@Override
protected Document createDocument() {
return new PDFDocument();
}
}
class WordApplication extends Application {
@Override
protected Document createDocument() {
return new WordDocument();
}
}
// Usage
public class FactoryMethodDemo {
public static void main(String[] args) {
Application app = new PDFApplication();
app.newDocument(); // Creates PDF without client knowing
app = new WordApplication();
app.newDocument(); // Creates Word document
}
}Created " + doc.getType() + " document
Abstract Factory Pattern
Creates families of related objects without specifying concrete classes.
| WindowsGUI | MacGUIFactory | |
|---|---|---|
| Factory |
--- Login Form ---
Factory with Java 8 (Functional Approach)
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class FunctionalFactory {
private static final Map<String, Supplier<Notification>> registry = new HashMap<>();
static {
registry.put("email", EmailNotification::new);
registry.put("sms", SMSNotification::new);
registry.put("push", PushNotification::new);
}
public static Notification create(String type) {
Supplier<Notification> supplier = registry.get(type.toLowerCase());
if (supplier == null) {
throw new IllegalArgumentException("Unknown notification type: " + type);
}
return supplier.get();
}
// Open for extension — register new types without modifying factory
public static void register(String type, Supplier<Notification> creator) {
registry.put(type.toLowerCase(), creator);
}
}
// Usage
FunctionalFactory.register("slack", SlackNotification::new);
Notification n = FunctionalFactory.create("slack");Interview Questions
Q1: What is the difference between Simple Factory, Factory Method, and Abstract Factory?
Answer: Simple Factory uses a static method with conditional logic (not a true pattern). Factory Method defines a creation interface, letting subclasses decide. Abstract Factory creates families of related products — it\'s a factory of factories.
Q2: How does Factory pattern support Open/Closed principle?
Answer: New product types can be added by creating new concrete classes and factories without modifying existing code. The client depends on abstractions, not concrete classes.
Q3: Where is Factory pattern used in Java standard library?
Answer: Calendar.getInstance(), NumberFormat.getInstance(), Collection.iterator(), DriverManager.getConnection(), DocumentBuilderFactory.newInstance().
Q4: When would you choose Factory Method over Abstract Factory?
Answer: Factory Method when you have one product hierarchy and want subclasses to choose the concrete type. Abstract Factory when you have multiple related product families that must be used together consistently.
Q5: How would you make a factory extensible at runtime?
Answer: Use a registry pattern (Map of type→creator). New types are registered with register(type, factory). Can use Supplier<T> or constructor references in Java 8+.
Summary
In this chapter, we learned about Factory Design Pattern in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Factory Design Pattern.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, design, patterns, factory
Related Java Master Course Topics