Knowledge Guide
HomeOO & Low-Level DesignStructural

Flyweight Pattern

The Flyweight Design Pattern is a structural design pattern that focuses on reducing the number of objects that need to be created, minimizing memory usage, and increasing performance. This pattern is especially useful when dealing with a large number of objects with similar states or configurations.

The key principle behind the Flyweight pattern is to separate the intrinsic state from the extrinsic state of an object:

Intrinsic State: This is the shared part of the state that is common across all objects and can be centralized. The intrinsic state is stored in the flyweights and is immutable.

Extrinsic State: This state varies between objects and cannot be shared. The client code must provide it when it uses the flyweight.

Flyweight objects are typically managed by a factory that ensures proper sharing. When a client requests a flyweight, the factory checks if an appropriate flyweight already exists and returns it; if not, it creates a new one.

Real World Example

A real-world example of the Flyweight pattern is seen in text editors that handle the formatting of characters in a document. If an editor did not use the Flyweight pattern, it would have to create a separate object for each character in the document, each storing its formatting information such as font size, style, and color. This would lead to a huge memory footprint, especially for large documents.

How Flyweight Pattern Applies:

Structure of Flyweight Pattern

The structural class diagram of the Flyweight Pattern contains the following components:

Flyweight Pattern - Class Diagram
Flyweight Pattern - Class Diagram

Implementation of Flyweight Pattern

The scenario:

Assume you are creating a particle system for a video game in which thousands of particles are rendered on screen, such as smoke, sparks, or magic effects. In addition to shared characteristics like texture, shape, and color, every particle possesses unique characteristics like position, velocity, and lifespan.

Flyweight Application:

Instead of storing texture, shape, and color for each particle, use the Flyweight Pattern to share these properties across all particles, significantly reducing the memory footprint.

The pseudocode for this example is as follows:

// Flyweight class for particle properties CLASS ParticleType PRIVATE texture, shape, color PRIVATE STATIC typesCache = {} STATIC METHOD createType(texture, shape, color) IF NOT typesCache.hasKey(texture + shape + color) typesCache[texture + shape + color] = new ParticleType(texture, shape, color) RETURN typesCache[texture + shape + color] CONSTRUCTOR(texture, shape, color) this.texture = texture this.shape = shape this.color = color // Context class for individual particles CLASS Particle PRIVATE x, y, velocityX, velocityY, lifespan, type CONSTRUCTOR(x, y, velocityX, velocityY, lifespan, type) this.x = x this.y = y this.velocityX = velocityX this.velocityY = velocityY this.lifespan = lifespan this.type = type METHOD update() // Update particle position and lifespan // ... METHOD draw() // Output the particle with its shared type properties PRINT "Drawing particle at (" + this.x + ", " + this.y + ") with texture: " + this.type.texture // Particle System class, acting as a client CLASS ParticleSystem PRIVATE particles = [] METHOD addParticle(x, y, velocityX, velocityY, lifespan, texture, shape, color) type = ParticleType.createType(texture, shape, color) particle = new Particle(x, y, velocityX, velocityY, lifespan, type) particles.add(particle) METHOD updateAndDraw() FOR particle IN particles particle.update() particle.draw() // Client code particleSystem = new ParticleSystem() particleSystem.addParticle(0, 0, 1, 1, 60, "SmokeTexture", "Circle", "Gray") particleSystem.addParticle(10, 10, 2, 2, 60, "SmokeTexture", "Circle", "Gray") particleSystem.updateAndDraw()

This example shows how the Flyweight Pattern can optimize a game's particle system, allowing for thousands of particles to be rendered without significant memory overhead.

Let's implement particle system example in programming languages.

Implementation

java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class ParticleType {

  private static Map<String, ParticleType> cache = new HashMap<>();
  private String texture, shape, color;

  private ParticleType(String texture, String shape, String color) {
    this.texture = texture;
    this.shape = shape;
    this.color = color;
  }

  public static ParticleType getParticleType(
    String texture,
    String shape,
    String color
  ) {
    String key = texture + shape + color;
    if (!cache.containsKey(key)) {
      cache.put(key, new ParticleType(texture, shape, color));
    }
    return cache.get(key);
  }

  public String getTexture() {
    return texture;
  }
  // Getters for shape, and color...
}

class Particle {

  private float x, y, velocityX, velocityY;
  private int lifespan;
  private ParticleType type;

  public Particle(
    float x,
    float y,
    float velocityX,
    float velocityY,
    int lifespan,
    ParticleType type
  ) {
    this.x = x;
    this.y = y;
    this.velocityX = velocityX;
    this.velocityY = velocityY;
    this.lifespan = lifespan;
    this.type = type;
  }

  public void update() {
    x += velocityX;
    y += velocityY;
    lifespan--;
  }

  public void draw() {
    System.out.println(
      "Drawing particle at (" +
      x +
      ", " +
      y +
      ") with texture: " +
      type.getTexture()
    );
  }
}

class ParticleSystem {

  private List<Particle> particles = new ArrayList<>();

  public void addParticle(
    float x,
    float y,
    float velocityX,
    float velocityY,
    int lifespan,
    String texture,
    String shape,
    String color
  ) {
    ParticleType type = ParticleType.getParticleType(texture, shape, color);
    particles.add(new Particle(x, y, velocityX, velocityY, lifespan, type));
  }

  public void simulate() {
    for (Particle particle : particles) {
      particle.update();
      particle.draw();
    }
  }
}

public class Solution {

  public static void main(String[] args) {
    ParticleSystem system = new ParticleSystem();
    system.addParticle(0, 0, 1, 1, 60, "SmokeTexture", "Circle", "Gray");
    system.addParticle(10, 10, 2, 2, 60, "SmokeTexture", "Circle", "Gray");
    system.simulate();
  }
}

Application of Flyweight Pattern

The Flyweight Pattern is especially useful in scenarios where the goal is to save memory by sharing as much data as possible between similar objects. Here are some specific applications where this pattern comes in handy:

In each application, the flyweight serves as a shared object that can be used in multiple contexts, each with its specific state. By using the intrinsic (shared) state effectively, the Flyweight Pattern ensures that the memory usage is optimized without compromising the application's functionality or design.

Pros and Cons

ProsCons
Memory Saver: It's great at reducing memory usage.Complexity Alert: It can make the system more complex.
Speed Booster: Less memory means faster performance.State Juggling: Managing intrinsic and extrinsic states can be tricky.
Scalability King: It can handle scaling up like a champ.Not Always Clear: For newcomers, the pattern might be a bit hard to grasp.

In short, Flyweight Pattern declutters your memory usage by sharing common data. It's super useful when you need to manage a lot of similar objects but don't want your memory crying for help. Just remember, it's a trade-off between memory efficiency and system complexity. Keep it in your toolkit for those memory-heavy scenarios!

🤖 Don't fully get this? Learn it with Claude

Stuck on Flyweight Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Flyweight Pattern** (OO & Low-Level Design) and want to truly understand it. Explain Flyweight Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Flyweight Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Flyweight Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Flyweight Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes