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
TypeScript example
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.