Menu
Coddy logo textTech

Factory Pattern

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 91 of 110.

The Factory pattern delegates object creation to a separate method or class, letting you create objects without specifying their exact class. This is different from the factory constructor you learned earlier - the Factory pattern is a design approach where creation logic is centralized and can return different types based on input.

Consider a scenario where you need to create different types of notifications. Instead of the client deciding which class to instantiate, a factory handles that decision:

abstract class Notification {
  void send(String message);
}

class EmailNotification implements Notification {
  @override
  void send(String message) => print('Email: $message');
}

class SMSNotification implements Notification {
  @override
  void send(String message) => print('SMS: $message');
}

class NotificationFactory {
  static Notification create(String type) {
    switch (type) {
      case 'email':
        return EmailNotification();
      case 'sms':
        return SMSNotification();
      default:
        return EmailNotification();
    }
  }
}

void main() {
  var notification = NotificationFactory.create('sms');
  notification.send('Hello!');  // SMS: Hello!
}

The client code doesn't need to know about EmailNotification or SMSNotification - it just asks the factory for a notification of a certain type. This makes adding new notification types easy: you only modify the factory, not every place that creates notifications.

Use the Factory pattern when object creation involves complex logic, when you want to hide implementation classes from clients, or when the exact type to create depends on runtime conditions.

challenge icon

Challenge

Easy

Let's build a document generator using the Factory pattern! You'll create a system that produces different types of documents (reports, invoices, and letters) through a centralized factory, so client code doesn't need to know about the specific document classes.

You'll organize your code into two files:

  • document_factory.dart: Create your document system here:
    • An abstract class Document with a method generate(String content) that returns a String
    • Three concrete classes that implement Document:
      • Report - its generate method returns === REPORT ===\n[content]\n=============
      • Invoice - its generate method returns INVOICE\n--------\n[content]\nTotal Due
      • Letter - its generate method returns Dear Reader,\n[content]\nSincerely
    • A DocumentFactory class with a static method create(String type) that returns the appropriate Document based on the type string: "report", "invoice", or "letter". For any unknown type, return a Letter as the default
  • main.dart: Import your document factory and demonstrate how the factory creates different document types without the client needing to know the concrete classes:
    • Use the factory to create a report and print the result of generating it with the content Sales increased by 25%
    • Print an empty line
    • Use the factory to create an invoice and print the result of generating it with the content Widget x3 - $150
    • Print an empty line
    • Use the factory to create a letter and print the result of generating it with the content Thank you for your order

Notice how your main file only interacts with the factory and the abstract Document type - it never directly creates Report, Invoice, or Letter objects!

Expected output:

=== REPORT ===
Sales increased by 25%
=============

INVOICE
--------
Widget x3 - $150
Total Due

Dear Reader,
Thank you for your order
Sincerely

Cheat sheet

The Factory pattern delegates object creation to a separate method or class, allowing you to create objects without specifying their exact class. Creation logic is centralized and can return different types based on input.

Basic structure of the Factory pattern:

abstract class Notification {
  void send(String message);
}

class EmailNotification implements Notification {
  @override
  void send(String message) => print('Email: $message');
}

class SMSNotification implements Notification {
  @override
  void send(String message) => print('SMS: $message');
}

class NotificationFactory {
  static Notification create(String type) {
    switch (type) {
      case 'email':
        return EmailNotification();
      case 'sms':
        return SMSNotification();
      default:
        return EmailNotification();
    }
  }
}

void main() {
  var notification = NotificationFactory.create('sms');
  notification.send('Hello!');  // SMS: Hello!
}

The client code only interacts with the factory and abstract type, not the concrete implementation classes. This makes adding new types easy - you only modify the factory.

Use the Factory pattern when:

  • Object creation involves complex logic
  • You want to hide implementation classes from clients
  • The exact type to create depends on runtime conditions

Try it yourself

import 'document_factory.dart';

void main() {
  // TODO: Use DocumentFactory.create() to create a report
  // Then print the result of generating it with content: "Sales increased by 25%"
  
  // TODO: Print an empty line
  
  // TODO: Use DocumentFactory.create() to create an invoice
  // Then print the result of generating it with content: "Widget x3 - \$150"
  
  // TODO: Print an empty line
  
  // TODO: Use DocumentFactory.create() to create a letter
  // Then print the result of generating it with content: "Thank you for your order"
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming