Structural Design Pattern
Flyweight Design Pattern in Java
Share reusable object state to reduce memory use when many similar objects are needed.
In this lesson: The Flyweight pattern separates intrinsic state that can be shared from extrinsic state supplied by the caller. This reduces duplicate objects in memory.
Implementation
final class CharacterStyle {
private final String font;
CharacterStyle(String font) { this.font = font; }
void draw(char value, int position) {
System.out.println(font + value + position);
}
}
Example usage
Map<String, CharacterStyle> styles = new HashMap<>();
CharacterStyle style = styles.computeIfAbsent("Roboto", CharacterStyle::new);
style.draw('A', 10);
style.draw('B', 20);
When should you use it?
Use Flyweight when many objects share repeated immutable state and memory usage matters. Keep changing values outside the shared flyweight.
Next step: Continue with the Design Patterns course.