Flyweight

Use sharing to support large numbers of fine-grained objects efficiently by separating intrinsic (shared, context-independent) state from extrinsic (context-dependent) state passed in by clients. Apply it when an application uses a large number of objects, storage costs are high due to object quantity, and most object state can be made extrinsic.

Examples:

  • In a particle-system game, millions of bullets all share the same color and sprite (intrinsic state stored once in a flyweight). Only position, velocity, and direction (extrinsic state) differ per bullet and are passed to render methods at runtime — reducing thousands of full-fat particle objects to a handful of shared flyweights plus lightweight context structs.
// ConcreteFlyweight stores only intrinsic state (character code)
class Character : public Glyph {
public:
  Character(char c) : _charcode(c) {}
  void Draw(Window* w, GlyphContext& gc) override;
  void SetFont(Font* f, GlyphContext& gc) override;
private:
  char _charcode;  // intrinsic; font/position passed as extrinsic via gc
};

// FlyweightFactory ensures sharing
class GlyphFactory {
public:
  Character* CreateCharacter(char c) {
    if (!_character[c]) _character[c] = new Character(c);
    return _character[c];
  }
private:
  Character* _character[NCHARCODES];
};

Synonyms: cache