Skip to main content
skill CX Codex

flyweight-pattern — Claude Code skill for cutting memory use

Teaches the agent to apply the flyweight pattern when lots of similar objects eat up memory.

MIT 634 installs ★ 259 updated 2026-04-15

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add PatternsDev/skills --skill flyweight-pattern -a claude-code
Open on GitHub

What flyweight-pattern does

The skill walks through splitting object state into intrinsic and extrinsic parts. Shared data goes into a Map and gets reused, so five book copies turn into three Book instances. The example uses a library where two copies share the same ISBN.

The code shows a createBook function that checks the Map by ISBN and returns an existing instance if one is already there. addBook then layers per-copy fields like availability and sales on top of that shared object.

The skill is explicit about when the pattern backfires. Few objects or almost no shared properties mean the split adds complexity without saving much. JavaScript's prototypal inheritance often covers the same ground with less machinery, and modern RAM sizes make the whole exercise optional in many projects.

What it helps with

  • reduce RAM usage when creating many similar objects
  • reuse instances that share the same ISBN
  • keep shared book data apart from per-copy fields
  • help the agent decide when flyweight is not worth it
  • cache objects through a Map

Example prompts for the agent

  • Apply the flyweight pattern to my Book class so identical ISBNs reuse one instance
  • Rewrite createBook to cache instances in a Map
  • Is splitting intrinsic and extrinsic state worth it here?

How to install flyweight-pattern

1Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill flyweight-pattern -a claude-code

2Manually: put the files in place

~/.claude/skills/flyweight-pattern/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/flyweight-pattern/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about flyweight-pattern

How do I install flyweight-pattern in Claude Code?

Run npx skills add PatternsDev/skills --skill flyweight-pattern -a claude-code. The skill file lands at ~/.claude/skills/flyweight-pattern/SKILL.md.

What does the flyweight-pattern skill do?

It teaches the agent to separate shared object state from per-instance state and cache the shared parts. This cuts memory use when many similar objects are created.

When should I skip the flyweight pattern?

When object counts are small, when there are few shared properties, or when lookup and management overhead outweighs the memory savings. In JavaScript, prototypal inheritance is often the simpler choice.

Source text

SKILL.md · MIT
---
name: flyweight-pattern
description: Teaches the flyweight pattern for memory optimization. Use when your application creates large numbers of similar objects and memory consumption is a concern.
paths:
  - "**/*.js"
  - "**/*.ts"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "module-pattern"
  - "singleton-pattern"
---

# Flyweight Pattern

The flyweight pattern is a useful way to conserve memory when we're creating a large number of similar objects.

In our application, we want users to be able to add books. All books have a `title`, an `author`, and an `isbn` number! However, a library usually doesn't have just one copy of a book: it usually has multiple copies of the same book.

## When to Use

- Use this when creating a huge number of objects that could potentially drain available memory
- This is helpful when many objects share the same intrinsic properties (e.g., books with the same ISBN)

## When NOT to Use

- When the number of objects is small enough that memory is not a concern
- When objects have few or no shared intrinsic properties — the separation of intrinsic and extrinsic state adds complexity without savings
- When the added lookup/management overhead outweighs the memory benefit

## Instructions

- Separate intrinsic (shared) state from extrinsic (unique) state
- Use a Map or similar structure to cache and reuse shared object instances
- Consider JavaScript's prototypal inheritance as a simpler alternative in many cases

## Details

It wouldn't be very useful to create a new book instance each time if there are multiple copies of the exact same book. Instead, we want to create multiple instances of the `Book` constructor, that represent a single book.

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

Let's create the functionality to add new books to the list. If a book has the same ISBN number, thus is the exact same book type, we don't want to create an entirely new `Book` instance. Instead, we should first check whether this book already exists.

```js
const books = new Map();

const createBook = (title, author, isbn) => {
  const existingBook = books.has(isbn);

  if (existingBook) {
    return books.get(isbn);
  }
};
```

If it doesn't contain the book's ISBN number yet, we'll create a new book and add its ISBN number to the `isbnNumbers` set.

```js
const createBook = (title, author, isbn) => {
  const existingBook = books.has(isbn);

  if (existingBook) {
    return books.get(isbn);
  }

  const book = new Book(title, author, isbn);
  books.set(isbn, book);

  return book;
};
```

The `createBook` function helps us create new instances of one type of book. However, a library usually contains multiple copies of the same book! Let's create an `addBook` function, which allows us to add multiple copies of the same book. It should invoke the `createBook` function, which returns either a newly created `Book` instance, or returns the already existing instance.

In order to keep track of the total amount of copies, let's create a `bookList` array that contains the total amount of books in the library.

```js
const bookList = [];

const addBook = (title, author, isbn, availability, sales) => {
  const book = {
    ...createBook(title, author, isbn),
    sales,
    availability,
    isbn,
  };

  bookList.push(book);
  return book;
};
```

Perfect! Instead of creating a new `Book` instance each time we add a copy, we can effectively use the already existing `Book` instance for that particular copy. Let's create 5 copies of 3 books: Harry Potter, To Kill a Mockingbird, and The Great Gatsby.

```js
addBook("Harry Potter", "JK Rowling", "AB123", false, 100);
addBook("Harry Potter", "JK Rowling", "AB123", true, 50);
addBook("To Kill a Mockingbird", "Harper Lee", "CD345", true, 10);
addBook("To Kill a Mockingbird", "Harper Lee", "CD345", false, 20);
addBook("The Great Gatsby", "F. Scott Fitzgerald", "EF567", false, 20);
```

Although there are 5 copies, we only have 3 `Book` instances!

The flyweight pattern is useful when you're creating a huge number of objects, which could potentially drain all available RAM. It allows us to minimize the amount of consumed memory.

In JavaScript, we can easily solve this problem through [prototypal inheritance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain). Nowadays, hardware has GBs of RAM, which makes the flyweight pattern less important.

## Source

- [patterns.dev/vanilla/flyweight-pattern](https://patterns.dev/vanilla/flyweight-pattern)

### References

- [Flyweight](https://refactoring.guru/design-patterns/flyweight) - Refactoring Guru
- [Flyweight Design Pattern](https://howtodoinjava.com/design-patterns/structural/flyweight-design-pattern) - How To Do In Java

© patterns.dev · MIT · PatternsDev/skills

Similar skills

All skills for Agent setup: memory, context, orchestration →

From the same set58

The whole set →
provider-pattern provider-pattern teaches your agent to move shared data into React Context and hand it out through a Provider when props crawl through every layer. CX Codex +1 642installs mixin-pattern Teaches the AI agent how to implement the mixin pattern in JavaScript and TypeScript without inheritance chains. CX Codex +1 638installs prototype-pattern Teaches coding assistants the JavaScript Prototype Pattern. It shows how to share methods via the prototype chain to keep memory consumption low. CX Codex +1 636installs proxy-pattern Teaches the JavaScript Proxy pattern: intercepting property reads and writes, adding validation and logging. Useful when your agent edits that kind of code. CX Codex +1 635installs mediator-pattern Teaches the mediator pattern: components talk through one central point instead of calling each other. Useful once those direct links get tangled. CX Codex +1 631installs components This skill guides Vue component structure, from single-file templates to reactive state and parent-child data flow. Use it when building an interface or splitting up a crowded component. CX Codex +1 212installs composables Teaches the agent to write Vue composables — reusable stateful logic with the Composition API. Use it when reactive state, computed properties or side effects are shared across components. CX Codex +1 211installs async-components Teaches the agent to load Vue components asynchronously via defineAsyncComponent(), so heavy modals and dialogs don't ship with the initial bundle. CX Codex +1 207installs

Project sponsors

Companies that keep this analytics open