Design patterns
patterns11FlyweightPattern
- Path
- pkg8patterns/patterns11FlyweightPattern.java
- Package
- pkg8patterns
- Study order
- 11
- Run
- Single-file source launch
- Command
- java pkg8patterns/patterns11FlyweightPattern.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg8patterns;2 3/*4 * Flyweight (Structural)5 * ----------------------6 * INTENT: share fine-grained objects to support large numbers efficiently by7 * separating intrinsic (shared) state from extrinsic (context) state.8 * UML: FlyweightFactory caches Flyweights; client passes extrinsic state per call.9 * PROS: huge memory savings when many objects share state.10 * CONS: complexity; must split state carefully.11 * REAL-WORLD: Integer.valueOf cache (-128..127), String pool, glyph rendering.12 */13import java.util.*;14 15public class patterns11FlyweightPattern {16 17 // Intrinsic (shared) state: the tree species18 static class TreeType {19 final String name, color;20 TreeType(String name, String color) { this.name = name; this.color = color; }21 String draw(int x, int y) { return name + "(" + color + ") at (" + x + "," + y + ")"; }22 }23 24 // Factory ensures one TreeType object per unique species25 static class TreeFactory {26 private final Map<String, TreeType> cache = new HashMap<>();27 TreeType get(String name, String color) {28 return cache.computeIfAbsent(name + "-" + color, k -> new TreeType(name, color));29 }30 int distinctTypes() { return cache.size(); }31 }32 33 public static void main(String[] args) {34 TreeFactory factory = new TreeFactory();35 // Plant 1000 trees but only a few shared TreeType objects exist36 List<String> forest = new ArrayList<>();37 for (int i = 0; i < 1000; i++) {38 TreeType type = factory.get(i % 2 == 0 ? "Oak" : "Pine", i % 2 == 0 ? "green" : "dark-green");39 forest.add(type.draw(i, i)); // extrinsic state (x,y) passed in40 }41 System.out.println("planted " + forest.size() + " trees");42 System.out.println("distinct shared TreeType objects = " + factory.distinctTypes());43 System.out.println("sample: " + forest.get(0));44 }45}