Menu
Coddy logo textTech

Factory Constructors

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

A factory constructor is a special constructor that doesn't always create a new instance. Unlike regular constructors, a factory constructor can return an existing instance, a subtype, or even null (if nullable). You declare it using the factory keyword.

class Logger {
  static final Logger _instance = Logger._internal();
  
  // Private named constructor
  Logger._internal();
  
  // Factory constructor
  factory Logger() {
    return _instance;
  }
}

Logger log1 = Logger();
Logger log2 = Logger();
print(identical(log1, log2)); // true

In this example, the factory constructor always returns the same instance. No matter how many times you call Logger(), you get the identical object. This pattern is commonly used for implementing singletons.

Factory constructors differ from regular constructors in a key way: they don't have access to this because they might not create a new instance at all. Instead, they must explicitly return an object:

class Shape {
  factory Shape(String type) {
    if (type == 'circle') return Circle();
    if (type == 'square') return Square();
    return Rectangle();
  }
}

class Circle extends Shape { Circle() : super._(); }
class Square extends Shape { Square() : super._(); }
class Rectangle extends Shape { Rectangle() : super._(); }

Factory constructors are useful when you need control over instance creation, such as returning cached objects, implementing object pools, or deciding which subtype to instantiate based on input parameters.

challenge icon

Challenge

Easy

Let's build a notification system that uses factory constructors to create different types of notifications based on a simple string input.

You'll create two files to organize your code:

  • notification.dart: Define a Notification class that serves as the base for all notification types. Your class should have:
    • A String message field
    • A private named constructor Notification._internal that initializes the message
    • A factory constructor Notification(String type, String message) that returns different notification subtypes based on the type parameter:
      • If type is 'email', return an EmailNotification
      • If type is 'sms', return an SMSNotification
      • Otherwise, return a PushNotification
    • A send() method that prints Sending: [message]

In the same file, create three subclasses that extend Notification:

  • EmailNotification: Override send() to print Email: [message]
  • SMSNotification: Override send() to print SMS: [message]
  • PushNotification: Override send() to print Push: [message]

Each subclass needs a constructor that takes a message and passes it to the parent using super._internal(message).

  • main.dart: Import your notification class and create three notifications using the factory constructor:
    • An email notification with message 'Welcome!'
    • An SMS notification with message 'Your code is 1234'
    • A push notification with message 'New update available'
    Call send() on each notification in the order listed above.

Expected output:

Email: Welcome!
SMS: Your code is 1234
Push: New update available

Cheat sheet

A factory constructor is a special constructor declared with the factory keyword that doesn't always create a new instance. Unlike regular constructors, it can return an existing instance, a subtype, or null.

Factory constructors don't have access to this and must explicitly return an object.

Singleton pattern example:

class Logger {
  static final Logger _instance = Logger._internal();
  
  Logger._internal(); // Private named constructor
  
  factory Logger() {
    return _instance; // Always returns same instance
  }
}

Logger log1 = Logger();
Logger log2 = Logger();
print(identical(log1, log2)); // true

Returning different subtypes:

class Shape {
  factory Shape(String type) {
    if (type == 'circle') return Circle();
    if (type == 'square') return Square();
    return Rectangle();
  }
}

class Circle extends Shape { Circle() : super._(); }
class Square extends Shape { Square() : super._(); }
class Rectangle extends Shape { Rectangle() : super._(); }

Factory constructors are useful for controlling instance creation, such as returning cached objects, implementing object pools, or deciding which subtype to instantiate based on input parameters.

Try it yourself

import 'notification.dart';

void main() {
  // TODO: Create an email notification with message 'Welcome!'
  
  // TODO: Create an SMS notification with message 'Your code is 1234'
  
  // TODO: Create a push notification with message 'New update available'
  
  // TODO: Call send() on each notification in 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