← Back to list

13.Factory Constructor

AFactory constructor is a constructor prefixed with the factory keyword that gives you control over how an object is created. Unlike a…

Aly Route · 2026-04-08 19:07 · 0 claps · 1.2 min read
#factory-pattern #dart-programming-language #dart
Open on Medium ↗
Wiki topics: 💻 · Programming

13.Factory Constructor

AFactory constructor is a constructor prefixed with the factory keyword that gives you control over how an object is created. Unlike a generative constructor (which always creates and returns a new instance of the current class), a factory acts more like a static method that returns an instance.

Why Using factory constructor?

1- It can return an existing object “a cached one” instead of always creating something brand new and wasting memory.

class Logger {
  final String name;
  static final Map<String, Logger> _cache = {};

  // Factory constructor checks the cache first
  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }

  // Private generative constructor
  Logger._internal(this.name);
}

void main() {
  var log1 = Logger('UI');
  var log2 = Logger('UI');
  print(identical(log1, log2)); // true - same instance!
}

2- It can return an instance of a subtype

This is the ultimate way to achieve loose coupling. The caller asks for a Shape, but the factory decides whether to give them a Circle or a Square.

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

class Circle implements Shape {
  @override
  void draw() => print("Drawing Circle");
}

class Square implements Shape {
  @override
  void draw() => print("Drawing Square");
}

3- perform non-trivial work prior to constructing an instance. This could include checking arguments or doing any other processing that can’t be handled in the initializer list.

class User {
  final String username;

  factory User.fromJson(Map<String, dynamic> json) {
    // Perform logic: validation, transformations, etc.
    final name = json['name']?.toString().toLowerCase() ?? 'guest';
    return User._internal(name);
  }

  User._internal(this.username);
}

Test Your Knowledge


메타데이터
post_id
b30a92fa18ca
slug
13-factory-constructor-b30a92fa18ca
url
https://medium.com/@aly.route/13-factory-constructor-b30a92fa18ca
canonical_url
https://medium.com/@aly.route/13-factory-constructor-b30a92fa18ca
author_url
https://medium.com/@aly.route
status
ok
fetched_at
2026-07-17 14:47:18