Simple Factory Design Pattern

Simple Factory Design Pattern

What is Simple factory design pattern

  • The simple factory design pattern is a creational design pattern that provides an Interface for creating objects without exposing the object creation logic to the client

  • It encapsulates the object creation code in a single class called a factory

Key benefit of Simple factory pattern

  • It encapsulated the object creation logic in one place, making the code easier to maintain

  • It provides a clear separation between the creation and use of objects

  • It makes adding new types of objects easier - just add a new call and update the factory method

Implementation

  1. Define a Common Product Interface:

// Document interface - follows Interface Segregation Principle
interface Document {
    void generate();
}

// Optional interface for printable documents - ISP
interface Printable {
    void print();
}
  1. Create Concrete Product Classes:

    Implement the concrete product classes that implement the product interface

// Concrete document classes
class PDFDocument implements Document, Printable {
    @Override
    public void generate() {
        System.out.println("Generating PDF document");
    }

    @Override
    public void print() {
        System.out.println("Printing PDF document");
    }
}

class WordDocument implements Document {
    @Override
    public void generate() {
        System.out.println("Generating Word document");
    }
}

class ExcelDocument implements Document {
    @Override
    public void generate() {
        System.out.println("Generating Excel document");
    }
}
  1. Create the Factory Class:

    The factory class will have a method to create objects based on input. The factory class will instantiate concrete product classes based on the given input type.

// Simple Factory - follows Single Responsibility Principle
class DocumentFactory {
    public Document createDocument(String type) {
        return switch (type.toLowerCase()) {
            case "pdf" -> new PDFDocument();
            case "word" -> new WordDocument();
            case "excel" -> new ExcelDocument();
            default -> throw new IllegalArgumentException("Unknown document type: " + type);
        };
    }
}
  1. Use the Factory:

    In client code, you use the factory to create objects without needing to know the exact type of the object being created.

public class Main {
    public static void main(String[] args) {
        DocumentFactory factory = new DocumentFactory();

        // Create and process PDF document
        Document pdfDoc = factory.createDocument("pdf");
        pdfDoc.generate();
        if(pdfDoc instanceof  Printable printable){
            printable.print();
        }

        // Create and process Word document
        Document wordDoc = factory.createDocument("word");
        wordDoc.generate();

    }
}

Demonstrate how simple factory design pattern follows SOLID principle

  1. Single Responsibility Principle

  • DocumentFactory has only one job: creating documents

  • Each document class handles only its specific document type

  1. Open/Closed Principle (OCP):
  • New document types can be added by creating new classes implementing the Document interface

  • No need to modify existing document classes

  • Factory can be extended without modifying existing code

  1. Liskov Substitution Principle (LSP):
  • Subtypes (PDFDocument, WordDocument, ExcelDocument) can be substituted for the base type (Document) without changing the expected behavior of the program.
  1. Interface Segregation Principle (ISP)
  • Document interface has only essential methods

  • Printable interface is separate for documents that support printing

  • Classes only implement interfaces they need

  1. Dependency Inversion Principle (DIP)
  • High-level modules depend on abstractions (Document interface), not on concrete document types.

  • Low-level modules depend on abstractions (implementing the Document interface), not on high-level modules.

  • Flexibility: You can easily add new document types (e.g., TextDocument) without modifying high-level modules like DocumentFactory. You just need to implement the Document interface.

Summary

Use the Simple Factory Pattern when:

  • You want to centralize object creation logic.

  • You want to abstract away complex or repetitive instantiation code.

  • You need to create objects based on some input or conditions.

  • You want to reduce the dependency on concrete classes in your client code.

It is best suited for simple scenarios where the number of product types is relatively small and doesn’t change frequently.

Did you find this article valuable?

Support Bharat's Blog by becoming a sponsor. Any amount is appreciated!