0Pricing
Clean Architecture & Design Patterns in Practice · Lesson

Flyweight Pattern for Memory Efficiency

Discover the Flyweight pattern, which shares fine-grained objects to support large numbers of instances with minimal memory.

Flyweight Pattern for Memory Efficiency is a free Clean Architecture & Design Patterns in Practice lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Clean Architecture & Design Patterns in Practice learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Memory Problem

Some applications must hold huge numbers of similar objects: characters in a document, tiles in a game, particles in a simulation.

Naively creating one full object per element can exhaust memory. The Flyweight pattern attacks this directly.

Core Idea: Share What Repeats

Flyweight splits an object state into two parts:

  • Intrinsic state: shared, context-independent (e.g. a glyph shape).
  • Extrinsic state: unique per use, passed in from outside (e.g. position).

Only the intrinsic part is stored once and reused.

A Concrete Scenario

Imagine rendering thousands of trees in a forest. Every tree of the same species shares the same texture and mesh.

Storing that texture once and reusing it across all instances is the essence of Flyweight.

The Flyweight Class

The flyweight holds only intrinsic, shareable data.

class TreeType {
    final String name;
    final String texture;
    TreeType(String name, String texture) {
        this.name = name;
        this.texture = texture;
    }
}

The Flyweight Factory

A factory ensures flyweights are created once and reused, returning the existing instance when possible.

class TreeTypeFactory {
    private static final Map<String, TreeType> pool = new HashMap<>();
    static TreeType get(String name, String tex) {
        return pool.computeIfAbsent(name, k -> new TreeType(name, tex));
    }
}

Passing Extrinsic State

The context object stores only the unique data and references the shared flyweight.

class Tree {
    final int x, y;
    final TreeType type;
    Tree(int x, int y, TreeType type) {
        this.x = x; this.y = y; this.type = type;
    }
}

Putting It Together

Thousands of Tree objects share a handful of TreeType flyweights.

public static void main(String[] args) {
    java.util.List<Tree> forest = new java.util.ArrayList<>();
    for (int i = 0; i < 100000; i++) {
        TreeType t = TreeTypeFactory.get("Oak", "oak.png");
        forest.add(new Tree(i, i, t));
    }
    System.out.println("Trees: " + forest.size());
}

Intrinsic vs Extrinsic Discipline

The pattern only works if intrinsic state is truly immutable and shared. If you mutate a flyweight, every context using it is affected.

Always make flyweight fields final.

Relationship to Other Patterns

  • The factory in Flyweight resembles an Object Pool, but pool objects are checked out exclusively while flyweights are shared concurrently.
  • Flyweights are often combined with Composite for tree-like shared structures.

When to Use It

Reach for Flyweight when:

  • You have a very large number of objects.
  • Storage cost is high due to repeated state.
  • That repeated state can be cleanly separated as intrinsic.

If object counts are modest, the indirection is not worth it.

Trade-offs

Flyweight trades CPU and complexity for memory. Passing extrinsic state on each call and looking up shared instances adds overhead. Use it only when memory is the real bottleneck.

Quick Check

Test your understanding of the Flyweight pattern.

Recap

You learned the Flyweight structural pattern.

  • Split state into intrinsic (shared) and extrinsic (per-use).
  • A factory reuses shared flyweights.
  • It trades CPU for large memory savings when instance counts are huge.

Frequently asked questions

Is the “Flyweight Pattern for Memory Efficiency” lesson free?

Yes — the full text of “Flyweight Pattern for Memory Efficiency” is free to read here on the web, and the Clean Architecture & Design Patterns in Practice course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Clean Architecture & Design Patterns in Practice course, upgrade to CoddyKit PRO.

What will I learn in “Flyweight Pattern for Memory Efficiency”?

Discover the Flyweight pattern, which shares fine-grained objects to support large numbers of instances with minimal memory. You practise Clean Architecture & Design Patterns in Practice with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Clean Architecture & Design Patterns in Practice?

No prior experience is required. Clean Architecture & Design Patterns in Practice on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Flyweight Pattern for Memory Efficiency” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Clean Architecture & Design Patterns in Practice lesson?

Yes. Every Clean Architecture & Design Patterns in Practice lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Adapter and Decorator Patterns
  2. Facade and Proxy Patterns
  3. Composite and Bridge Patterns
  4. Flyweight Pattern for Memory Efficiency
← Back to Clean Architecture & Design Patterns in Practice