Explain the Flyweight pattern.

Topic: design-patterns, Structural Patterns. Level: Hard.

Answer

Flyweight minimizes memory by **sharing** common, immutable parts of many similar objects (intrinsic state) and passing the varying parts (extrinsic state) in from outside. Instead of millions of objects each holding duplicate data, you cache and reuse shared instances. Classic uses: characters/glyphs in a text editor, particles in a game, or Java's `Integer.valueOf` cache. Requires clearly separating shared (intrinsic) from context-specific (extrinsic) state. ```java // Intrinsic (shared) state — cached and reused record TreeType(String name, String texture) {} // immutable, shared class TreeFactory { private static final Map<String, TreeType> cache = new HashMap<>(); static TreeType of(String name, String texture) { return cache.computeIfAbsent(name + texture, k -> new TreeType(name, texture)); } } // Extrinsic (varying) state passed in per instance: void draw(TreeType type, int x, int y) { /* render type at x,y */ } // 1,000,000 trees share a handful of TreeType objects. ```