Structural Design Pattern · Java

Flyweight Design Pattern in Java

Reuse shared objects to reduce memory usage when many objects have common data.

What is Flyweight?

Flyweight separates intrinsic shared state from extrinsic per-use state. A factory returns an existing object when possible.

Beginner-friendly Java example

The following example shows the central idea of this pattern in a small, practical scenario.

record Icon(String name) { }

class IconFactory {
    private final Map<String, Icon> cache = new HashMap<>();

    Icon get(String name) {
        return cache.computeIfAbsent(name, Icon::new);
    }
}

IconFactory factory = new IconFactory();
Icon first = factory.get("warning");
Icon second = factory.get("warning");
System.out.println(first == second); // true

Benefits and trade-offs

Benefits
  • Separates responsibilities clearly.
  • Improves flexibility as the application grows.
  • Encapsulates structural complexity.
Trade-offs
  • Can introduce extra wrapper classes.
  • Choose the pattern only when the complexity is real.

When should you use it?

  • Text character formatting
  • Game objects sharing textures
  • Large collections of repeated icons
Key takeawayReuse shared objects to reduce memory usage when many objects have common data. Start with the smallest structure that solves the coupling or composition problem.