Sobes.tech
Junior — Middle

Can you list the main design patterns related to object creation?

sobes.tech AI

Answer from AI

Main design patterns related to object creation include:

  • Singleton — ensures that a class has only one instance and provides a global point of access to it.
  • Factory Method — defines an interface for creating an object, allowing subclasses to decide which class to instantiate.
  • Abstract Factory — provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  • Builder — separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
  • Prototype — creates new objects by copying existing ones (cloning).

Example of Factory Method in Dart (Flutter):

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
}
Can you list the main design patterns related to… - sobes.tech