Question #262MediumArchitecture

What are all the design patterns in generic means ?

Answer

Overview

Design Patterns are reusable solutions to commonly occurring problems in software design. They are not code — they are templates/blueprints for solving recurring design problems.

There are 23 classic design patterns organized into 3 categories by the Gang of Four (GoF).


3 Categories of Design Patterns

CategoryPurposeCount
CreationalHow objects are created5 patterns
StructuralHow objects are composed/structured7 patterns
BehavioralHow objects communicate/interact11 patterns

1. Creational Patterns

Deal with object creation mechanisms.

PatternDescriptionFlutter Example
SingletonOnly one instance of a class
text
GetIt
,
text
ApiClient
,
text
Logger
Factory MethodSubclasses decide which object to create
text
Widget build()
,
text
factory
constructors
Abstract FactoryCreate families of related objectsTheme factories
BuilderConstruct complex objects step-by-step
text
AlertDialog
,
text
SnackBar
builders
PrototypeClone existing objects
text
copyWith()
on models

Singleton Example (Dart)

dart
class AppLogger {
  static final AppLogger _instance = AppLogger._internal();
  factory AppLogger() => _instance;
  AppLogger._internal();

  void log(String msg) => print('[LOG] $msg');
}

Factory Method Example (Dart)

dart
abstract class Button {
  Widget build();

  // Factory decides which button to create
  factory Button(String platform) {
    if (platform == 'ios') return IOSButton();
    return AndroidButton();
  }
}

Builder Example (Dart)

dart
class QueryBuilder {
  String _table = '';
  String? _where;
  int? _limit;

  QueryBuilder from(String table) { _table = table; return this; }
  QueryBuilder where(String condition) { _where = condition; return this; }
  QueryBuilder limit(int n) { _limit = n; return this; }

  String build() => 'SELECT * FROM $_table'
      '${_where != null ? ' WHERE $_where' : ''}'
      '${_limit != null ? ' LIMIT $_limit' : ''}';
}

// Usage
final query = QueryBuilder()
    .from('users')
    .where('age > 18')
    .limit(10)
    .build();

2. Structural Patterns

Deal with how classes and objects are composed.

PatternDescriptionFlutter Example
AdapterConvert one interface to anotherWrapping a library to match your interface
BridgeSeparate abstraction from implementationPlatform-specific implementations
CompositeTree structure of objectsFlutter Widget tree
DecoratorAdd behavior without modifying class
text
ClipRRect
,
text
Padding
,
text
Opacity
wrapping widgets
FacadeSimplified interface to complex systemRepository hiding API + DB complexity
FlyweightShare data to support many objects efficiently
text
const
widgets in Flutter
ProxySurrogate for another objectCaching proxy for API calls

Decorator Example (Dart)

dart
abstract class DataSource {
  String readData();
}

class FileDataSource implements DataSource {
  
  String readData() => 'Raw File Data';
}

// Decorator adds encryption without changing FileDataSource
class EncryptedDataSource implements DataSource {
  final DataSource _wrappee;
  EncryptedDataSource(this._wrappee);

  
  String readData() => 'ENCRYPTED(${_wrappee.readData()})';
}

// Usage
DataSource source = EncryptedDataSource(FileDataSource());
print(source.readData()); // ENCRYPTED(Raw File Data)

Facade Example (Dart)

dart
// Facade hides complexity of multiple systems
class AuthFacade {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  Future<void> signUp(String email, String password) async {
    final credential = await _auth.createUserWithEmailAndPassword(
      email: email, password: password);
    await _db.collection('users').doc(credential.user!.uid).set({
      'email': email, 'createdAt': FieldValue.serverTimestamp()
    });
  }
}

3. Behavioral Patterns

Deal with communication between objects.

PatternDescriptionFlutter Example
ObserverNotify dependents on state change
text
ChangeNotifier
,
text
Stream
,
text
BLoC
StrategySwap algorithms at runtimeSorting strategies, payment methods
CommandEncapsulate request as an objectUndo/Redo operations
StateChange behavior based on stateNavigation state, auth state
IteratorTraverse collection without exposing internalsDart's
text
Iterable
Template MethodDefine skeleton; subclasses fill in steps
text
StatefulWidget
lifecycle
Chain of ResponsibilityPass request along a chainMiddleware, interceptors
MediatorCentralize communicationEventBus, BLoC as mediator
MementoCapture and restore stateUndo feature
VisitorAdd operations without changing classesCode analyzers
InterpreterGrammar interpreterQuery language parsers

Observer Example (Dart)

dart
// Observable (Subject)
class Cart extends ChangeNotifier {
  List<String> _items = [];

  List<String> get items => _items;

  void addItem(String item) {
    _items.add(item);
    notifyListeners(); // Notifies all observers (Widgets)
  }
}

// Observer (View)
Consumer<Cart>(
  builder: (context, cart, child) {
    return Text('Items: ${cart.items.length}');
  },
)

Strategy Example (Dart)

dart
abstract class SortStrategy {
  List<int> sort(List<int> data);
}

class BubbleSort implements SortStrategy {
  
  List<int> sort(List<int> data) {
    // bubble sort implementation
    return data..sort();
  }
}

class QuickSort implements SortStrategy {
  
  List<int> sort(List<int> data) {
    // quick sort implementation
    return data..sort();
  }
}

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

  void setStrategy(SortStrategy strategy) => _strategy = strategy;
  List<int> sort(List<int> data) => _strategy.sort(data);
}

// Swap strategy at runtime
final sorter = Sorter(BubbleSort());
sorter.setStrategy(QuickSort()); // Switch algorithm without changing Sorter

Design Patterns Most Common in Flutter

PatternUsed In
Singleton
text
GetIt
, shared services
Observer
text
ChangeNotifier
,
text
BLoC
,
text
Riverpod
Factory
text
factory
constructors, named constructors
BuilderWidget APIs,
text
ThemeData
,
text
AppBar
DecoratorWidget wrapping (
text
Padding
,
text
ClipRRect
)
FacadeRepository pattern
StrategyDifferent state management approaches

Key Insight: Flutter's entire widget system is built on the Composite pattern — every widget is a tree of smaller widgets composited together.