Flyweight
Share common state between multiple objects
Overview
The Flyweight pattern is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.
Key Concepts
Intrinsic State: Shared data that is independent of the flyweight's context
Extrinsic State: Context-dependent data passed from the client
Flyweight Factory: Manages pool of existing flyweights
Saves memory by reusing identical state
Code Example
1// Flyweight (Intrinsic State)
2public class TreeType {
3 private String name;
4 private String color;
5 private String texture;
6
7 public TreeType(String name, String color, String texture) {
8 this.name = name;
9 this.color = color;
10 this.texture = texture;
11 }
12
13 public void draw(int x, int y) {
14 System.out.println("Drawing " + name + " tree of color " + color + " at (" + x + "," + y + ")");
15 }
16}
17
18// Flyweight Factory
19import java.util.HashMap;
20import java.util.Map;
21
22public class TreeFactory {
23 private static Map<String, TreeType> treeTypes = new HashMap<>();
24
25 public static TreeType getTreeType(String name, String color, String texture) {
26 String key = name + "-" + color + "-" + texture;
27 if (!treeTypes.containsKey(key)) {
28 treeTypes.put(key, new TreeType(name, color, texture));
29 System.out.println("Created new TreeType: " + name);
30 }
31 return treeTypes.get(key);
32 }
33}
34
35// Context Object (Extrinsic State)
36public class Tree {
37 private int x;
38 private int y;
39 private TreeType type;
40
41 public Tree(int x, int y, TreeType type) {
42 this.x = x;
43 this.y = y;
44 this.type = type;
45 }
46
47 public void draw() {
48 type.draw(x, y);
49 }
50}
51
52// Client
53import java.util.ArrayList;
54import java.util.List;
55
56public class Forest {
57 private List<Tree> trees = new ArrayList<>();
58
59 public void plantTree(int x, int y, String name, String color, String texture) {
60 TreeType type = TreeFactory.getTreeType(name, color, texture);
61 Tree tree = new Tree(x, y, type);
62 trees.add(tree);
63 }
64
65 public void draw() {
66 for (Tree tree : trees) {
67 tree.draw();
68 }
69 }
70
71 public static void main(String[] args) {
72 Forest forest = new Forest();
73 // Plants 100 trees, but only creates 2 TreeType objects (intrinsic state)
74 for (int i = 0; i < 50; i++) {
75 forest.plantTree(i, i, "Oak", "Green", "Rough");
76 forest.plantTree(i*2, i*2, "Pine", "Dark Green", "Smooth");
77 }
78 forest.draw();
79 }
80}The intrinsic state (name, color, texture) is shared among thousands of tree objects, drastically reducing RAM usage. The specific coordinates (extrinsic state) remain with each Tree object.
💡 Interview Tips
Java String Pool is real-world example of Flyweight.
Always clarify intrinsic (shared) vs extrinsic (context) state.
Show memory advantage: (Size of all instances) vs (Size of shared pool + size of extrinsic arrays).