Posts

Flyweight

June 24, 2025
Flyweight Pattern
Flyweight is a structural design pattern used to save memory by sharing common parts of state (data) across many similar objects, rather than storing full copies of the data in each object.
To reduce RAM usage when your program needs to create many objects, especially if those objects share similar data. Think of it like using a shared copy of something rather than creating a new one every time.

  • In a game, you have thousands of particles (bullets, missiles).
  • Each particle stores its own copy of color, image, and position.
  • Game crashes on low-RAM devices because too much memory is used.
  • Move shared data (like color, sprite) to a flyweight.
  • Keep unique data (like position, speed) outside, in a context object.
  • Now, instead of 1000 full particles, you store 1 flyweight per type (bullet, missile, shrapnel) and reuse it.

Here’s a simplified example using trees in a forest. You create 1000 tree objects. Each tree stores:
  • Position
  • Name
  • Color
  • Texture
πŸ’₯ Waste of memory! Because all trees may share name, color, and texture.
Pseudo
// Flyweight: shared part
class TreeType {
    name
    color
    texture
    draw(x, y)  // takes position as parameter
}

// Factory to manage and reuse TreeTypes
class TreeFactory {
    static treeTypes = []
    static getTreeType(name, color, texture) {
        if not found in treeTypes:
            create new TreeType
        return existing TreeType
    }
}

// Context: unique part
class Tree {
    x, y
    type: TreeType
    draw() {
        type.draw(x, y)
    }
}
πŸ‘¨β€πŸ’» Now, 1000 trees may only use 3 TreeTypes shared among them β€” saving memory!
  1. Identify common data: make it intrinsic (put in flyweight).
  2. Separate unique data: make it extrinsic (pass it in).
  3. Create a factory to manage flyweights.
  4. Use flyweights instead of full objects wherever possible.

Use it when:
  • You need tons of similar objects
  • Memory is tight (e.g., mobile games, graphics apps)
  • Many objects have repeating/shared data

Pros:
  • βœ… Big memory savings
  • βœ… Makes apps faster on low-spec systems
Cons:
  • ❌ More complex code
  • ❌ Slight CPU cost (extrinsic data must be passed every time)
On this page