Sobes.tech
Junior — Middle

Can you explain what the factory method pattern is and what it is used for?

sobes.tech AI

Answer from AI

The "Factory Method" pattern is a creational design pattern that defines an interface for creating an object but allows subclasses to decide which class to instantiate. This means object creation is delegated to subclasses, providing flexibility and extensibility.

In Flutter and Dart, this pattern is often used when there is a need to create different widgets or objects with a common interface, but the specific implementation is chosen dynamically.

Example:

abstract class Button {
  void render();
}

class AndroidButton implements Button {
  @override
  void render() => print('Android Button');
}

class IOSButton implements Button {
  @override
  void render() => print('iOS Button');
}

abstract class Dialog {
  Button createButton();

  void render() {
    var button = createButton();
    button.render();
  }
}

class AndroidDialog extends Dialog {
  @override
  Button createButton() => AndroidButton();
}

class IOSDialog extends Dialog {
  @override
  Button createButton() => IOSButton();
}

void main() {
  Dialog dialog = AndroidDialog();
  dialog.render(); // Outputs: Android Button

  dialog = IOSDialog();
  dialog.render(); // Outputs: iOS Button
}

This approach helps isolate object creation code and makes it easier to add new types without modifying existing code.