Creational Patterns  «Prev  Next»

Factory Method Pattern

The Factory Method Pattern is a creational design pattern in object-oriented programming. It defines an interface (a contract defining methods a class must implement) for creating objects but allows subclasses (classes that inherit from a parent class) to decide which specific class to instantiate. This promotes loose coupling, as client code interacts with interfaces rather than concrete classes, making it easier to extend systems with new object types.

Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory Method defers instantiation to subclasses.

Structure

The pattern includes:

Diagram Description: The Factory Method Pattern diagram shows an Abstract Product interface linked to a Concrete Product class via inheritance. An Abstract Creator defines the factory method, implemented by a Concrete Creator that instantiates the Concrete Product. Arrows indicate inheritance and instantiation relationships.

Code Example (Java)

Below is a Java implementation for creating different loggers:


// Abstract Product
interface Logger {
    void log(String message);
}

// Concrete Product
class ConsoleLogger implements Logger {
    public void log(String message) {
        System.out.println("Console: " + message);
    }
}

// Abstract Creator
abstract class LoggerCreator {
    abstract Logger createLogger();
}

// Concrete Creator
class ConsoleLoggerCreator extends LoggerCreator {
    Logger createLogger() {
        return new ConsoleLogger();
    }
}

// Client Code
public class Main {
    public static void main(String[] args) {
        LoggerCreator creator = new ConsoleLoggerCreator();
        Logger logger = creator.createLogger();
        logger.log("This is a test message.");
    }
}
    

More Factory Method Java Examples

Benefits

  1. Loose Coupling: Client code uses interfaces, allowing new classes to be added without modifying existing code.
  2. Flexibility: Subclasses can create customized objects, supporting extensibility.
  3. Encapsulation: Object creation logic is centralized, reducing duplication and improving maintainability.

Drawbacks

  1. Increased Complexity: Additional classes and interfaces can complicate small projects.
  2. Overhead: May be unnecessary for simple applications where direct object creation suffices.

When to Use

Use the Factory Method Pattern when:

  1. A class cannot predict the type of objects it needs to create.
  2. Subclasses need to specify which objects to create.
  3. Object creation logic should be localized to subclasses for modularity.

Comparison with Abstract Factory Pattern

The Factory Method Pattern is often confused with the Abstract Factory Pattern. Here’s how they differ:

Aspect Factory Method Abstract Factory
Purpose Creates one type of object, with subclasses choosing the specific class. Creates families of related objects without specifying concrete classes.
Scope Focuses on a single product type. Handles multiple product types.
Example Creating different loggers (e.g., console, file). Creating UI components for different themes (e.g., Windows, Mac).

Real-World Example

Hotel Analogy: At a hotel, the front desk (Creator) assigns a room (Product) when you check in. You request a room (Abstract Product), and the desk provides a specific type (Concrete Product, e.g., suite) without you needing to know the details.

Software Example: In a logging framework, a LoggerFactory (Creator) creates a Logger (Product). Based on configuration, it provides a ConsoleLogger or FileLogger, allowing client code to log messages without knowing the logger’s implementation.

Further Reading

Learn more at GoF Patterns.


SEMrush Software 3 SEMrush Banner 3