design-patterns

Quick-reference guide to software design patterns with concise Dart examples.

View project on GitHub

Defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.

Eliminates conditional statements for selecting behaviors.

typedef SortStrategy = void Function(List<int> data);

void bubbleSort(List<int> data) {
  print('Bubble sorting $data');
  data.sort();
}

void quickSort(List<int> data) {
  print('Quick sorting $data');
  data.sort();
}

class Sorter {
  SortStrategy strategy;
  Sorter(this.strategy);

  void sort(List<int> data) => strategy(data);
}

// Usage
final sorter = Sorter(bubbleSort);
sorter.sort([3, 1, 2]); // Bubble sorting [3, 1, 2]

sorter.strategy = quickSort;
sorter.sort([5, 4, 6]); // Quick sorting [5, 4, 6]