# Flyweight

> Share common state between thousands of similar objects instead of duplicating it in each — trade CPU for RAM when you're running out of memory.

- **Category**: Software Design
- **Subcategory**: structural
- **Canonical URL**: https://designpattern.fyi/patterns/flyweight/

---

## Description
**Intent**: Reduce memory consumption by sharing the intrinsic (shared) state across many similar objects, keeping only the extrinsic (unique) state per instance.

**Context**: You're rendering 100,000 trees in a game world, each with a position, scale, and type. Storing the full mesh, texture, and material for each tree object would exhaust RAM. Most trees of the same type share identical visual data — only their position differs.

**Solution**: Split object state into intrinsic (shared, immutable — tree type, texture, mesh) and extrinsic (unique per instance — position, scale). Create one Flyweight object per intrinsic state combination. Pass extrinsic state as method arguments. A FlyweightFactory caches and returns shared instances.


## Use Cases
Use only when you need a huge number of similar objects and memory consumption is a concrete problem — particle systems, game entities, text rendering, tile maps.



## Implementation Example

```javascript
class Book {
  constructor(title, author, isbn) {
    this.title = title;
    this.author = author;
    this.isbn = isbn;
  }
}

class BookFactory {
  constructor() { this.books = new Map(); }
  createBook(title, author, isbn) {
    if (!this.books.has(isbn)) {
      this.books.set(isbn, new Book(title, author, isbn));
    }
    return this.books.get(isbn);
  }
}

```



## Trade-offs


### Advantages

- Massive RAM savings when thousands of objects share the same core data.




### Considerations & Drawbacks

- Adds CPU cost when shared data needs recalculation with per-instance context.

- Code becomes significantly more complex — separating intrinsic/extrinsic state isn't always obvious.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/flyweight)

