For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/design-patterns/structural/flyweight.md.

Share common state between many objects to reduce memory usage. You have many similar objects with small variations. Memory usage is a concern

Flyweight

Overview

Share common state between many objects to reduce memory usage.

When to use

  • You have many similar objects with small variations.
  • Memory usage is a concern.

Java example

class Glyph {
    private final String font;
    Glyph(String font) { this.font = font; }
    String render(String text) { return font + ":" + text; }
}

class GlyphFactory {
    private final Map<String, Glyph> cache = new HashMap<>();
    Glyph get(String font) {
        return cache.computeIfAbsent(font, Glyph::new);
    }
}

TypeScript example

class Glyph {
  constructor(private font: string) {}
  render(text: string): string {
    return `${this.font}:${text}`;
  }
}

class GlyphFactory {
  private cache = new Map<string, Glyph>();
  get(font: string): Glyph {
    if (!this.cache.has(font)) {
      this.cache.set(font, new Glyph(font));
    }
    return this.cache.get(font)!;
  }
}

Pros and cons

Pros:

  • Reduces memory usage.
  • Improves performance for large sets.

Cons:

  • Adds complexity and indirection.
  • Requires careful separation of shared vs unique state.

Common pitfalls

  • Sharing mutable state across instances.
  • Over-optimizing when object counts are small.