Sobes.tech
Junior — Middle

Can you provide an example of implementing the factory method pattern in code?

sobes.tech AI

Answer from AI

The factory method pattern allows creating objects without specifying the exact class of the object being created. In Flutter, this is useful for creating widgets with different logic.

Example implementation in Dart:

abstract class Button {
  void render();
}

class AndroidButton implements Button {
  @override
  void render() {
    print('Render Android style button');
  }
}

class IOSButton implements Button {
  @override
  void render() {
    print('Render iOS style button');
  }
}

abstract class Dialog {
  Button createButton();

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

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

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

void main() {
  Dialog dialog;

  // Depending on the platform, create the appropriate dialog
  bool isAndroid = true;
  if (isAndroid) {
    dialog = AndroidDialog();
  } else {
    dialog = IOSDialog();
  }

  dialog.render();
}

In this example, the factory method createButton allows subclasses to create objects of different button types, and the client code works with abstractions.

Can you provide an example of implementing the… - sobes.tech