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
EasyLet'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
Documentwith a methodgenerate(String content)that returns aString - Three concrete classes that implement
Document:Report- itsgeneratemethod returns=== REPORT ===\n[content]\n=============Invoice- itsgeneratemethod returnsINVOICE\n--------\n[content]\nTotal DueLetter- itsgeneratemethod returnsDear Reader,\n[content]\nSincerely
- A
DocumentFactoryclass with a static methodcreate(String type)that returns the appropriateDocumentbased on the type string:"report","invoice", or"letter". For any unknown type, return aLetteras the default
- An abstract class
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
- Use the factory to create a report and print the result of generating it with the content
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
SincerelyCheat 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"
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor