A factory constructor in Dart

In Dart, a factory constructor is a special type of constructor that provides greater control over instance creation. Unlike generative constructors, which always produce a new instance of a class, factory constructors can return existing instances, new instances, or even instances of subtypes. This flexibility is particularly useful in scenarios such as implementing singletons, caching, or complex initialization logic.

Key Characteristics of Factory Constructors:

  • Instance Control: Factory constructors can decide whether to return a new instance or an existing one, enabling patterns like singletons or caching.

  • Subtype Instantiation: They can return instances of subtypes, allowing for more flexible and dynamic object creation.

  • Complex Initialization: Factory constructors can handle complex initialization logic that generative constructors might not be able to manage efficiently.

Basic Syntax:

To define a factory constructor, use the factory keyword followed by the class name and the constructor body.

class ClassName {
  // Factory constructor
  factory ClassName(parameters) {
    // Initialization logic
    return instance;
  }
}

Trivial Examples:

  1. Singleton Pattern:

    The singleton pattern ensures that a class has only one instance throughout the application’s lifecycle. A factory constructor can enforce this by returning the existing instance if it exists.

    class Singleton {
      // Private static variable to hold the single instance
      static Singleton? _instance;
    
      // Private named constructor to prevent direct instantiation
      Singleton._internal();
    
      // Factory constructor
      factory Singleton() {
        // Return existing instance if available; otherwise, create a new one
        return _instance ??= Singleton._internal();
      }
    
      // Example method
      void showMessage() {
        print('This is a singleton instance.');
      }
    }
    
    void main() {
      var s1 = Singleton();
      var s2 = Singleton();
    
      // Both s1 and s2 refer to the same instance
      print(identical(s1, s2)); // Outputs: true
    
      s1.showMessage(); // Outputs: This is a singleton instance.
    }
    

    In this example:

    • The Singleton class has a private static variable _instance that holds the single instance.

    • The private constructor Singleton._internal() prevents direct instantiation from outside the class.

    • The factory constructor checks if _instance is null. If it is, it creates a new instance; otherwise, it returns the existing instance.

  2. Returning Subtypes:

    Factory constructors can return instances of subtypes based on specific conditions, providing flexibility in object creation.

    abstract class Shape {
      // Factory constructor
      factory Shape(String type) {
        if (type == 'circle') {
          return Circle();
        } else if (type == 'square') {
          return Square();
        } else {
          throw 'Invalid shape type';
        }
      }
    
      void draw();
    }
    
    class Circle implements Shape {
      @override
      void draw() {
        print('Drawing a circle.');
      }
    }
    
    class Square implements Shape {
      @override
      void draw() {
        print('Drawing a square.');
      }
    }
    
    void main() {
      Shape shape1 = Shape('circle');
      shape1.draw(); // Outputs: Drawing a circle.
    
      Shape shape2 = Shape('square');
      shape2.draw(); // Outputs: Drawing a square.
    }
    

    In this example:

    • The Shape class is an abstract class with a factory constructor that returns different subtypes (Circle or Square) based on the provided type.

    • The draw method is implemented differently in each subtype.

  3. Caching Instances:

    Factory constructors can implement caching to return existing instances with the same state, reducing unnecessary object creation.

    class Color {
      final int red;
      final int green;
      final int blue;
    
      // Private constructor
      Color._internal(this.red, this.green, this.blue);
    
      // Cache to store instances
      static final Map<String, Color> _cache = {};
    
      // Factory constructor
      factory Color(int red, int green, int blue) {
        final key = '$red-$green-$blue';
    
        // Return existing instance if found in cache; otherwise, create a new one
        return _cache.putIfAbsent(key, () => Color._internal(red, green, blue));
      }
    }
    
    void main() {
      var color1 = Color(255, 0, 0);
      var color2 = Color(255, 0, 0);
      var color3 = Color(0, 255, 0);
    
      print(identical(color1, color2)); // Outputs: true
      print(identical(color1, color3)); // Outputs: false
    }
    

    In this example:

    • The Color class uses a factory constructor to check if an instance with the same RGB values exists in the _cache.

    • If it exists, the cached instance is returned; otherwise, a new instance is created and added to the cache.

Conclusion:

Factory constructors in Dart provide a powerful mechanism for controlling instance creation, enabling patterns like singletons, caching, and the ability to return subtypes. By understanding and utilizing factory constructors, you can write more efficient and flexible Dart code.

For more detailed information and examples, you can refer to the Dart Language Tour on Constructors.

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free