design-patterns

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

View project on GitHub

Shares common state across many objects to save memory.

Separates intrinsic (shared) state from extrinsic (unique) state.

class TreeType {
  final String name;
  final String texture; // heavy shared data

  TreeType(this.name, this.texture);
}

class TreeFactory {
  static final Map<String, TreeType> _cache = {};

  static TreeType get(String name, String texture) {
    return _cache.putIfAbsent(name, () => TreeType(name, texture));
  }
}

class Tree {
  final int x, y; // extrinsic state (unique per tree)
  final TreeType type; // intrinsic state (shared)

  Tree(this.x, this.y, this.type);
}

// Usage: 1000 trees but only a few TreeType objects in memory
final oak = TreeFactory.get('Oak', 'oak_texture.png');
final trees = [for (var i = 0; i < 1000; i++) Tree(i, i * 2, oak)];