Flyweight Pattern
Share common state efficiently among large numbers of objects
Pattern Overview
ðŠķ Flyweight Pattern
The Flyweight Pattern minimizes memory usage by sharing common data among multiple objects. It separates intrinsic state (shared) from extrinsic state (context-specific).
Core Concepts
ðđ Intrinsic State - Data that can be shared among multiple objects
ðđ Extrinsic State - Context-specific data passed to operations
ðđ Factory - Ensures flyweights are shared, not duplicated
ðđ Context - Stores extrinsic state and references flyweight
Real-World Applications
Text Editors - Character objects share font/style data, position is unique Game Development - Tree sprites shared, position/health are individual Particle Systems - Particle behaviors shared, position/velocity unique Web Browsers - CSS styles shared among elements with same propertiesMemory Optimization
Before: 1000 characters = 1000 complete objects After: 1000 characters = 26 shared flyweights + 1000 contexts Savings: ~95% memory reduction for typical textImplementation Benefits
â
Massive memory savings - Shared intrinsic state reduces object count
â
Performance gains - Fewer objects mean less garbage collection
â
Scalable design - Handles thousands of objects efficiently
â
Transparent sharing - Client code doesn't need to manage sharing
Examples:
const doc = createTextDocument();
console.log(`Characters: ${doc.getCharacterCount()}`);
console.log(`Flyweights: ${doc.getFlyweightCount()}`);
console.log(doc.render().split('\n').slice(0, 3).join('\n'));Characters: 46
Flyweights: 15
Render 'H' in Arial at (0, 0) size:12 color:black
Render 'e' in Arial at (10, 0) size:12 color:black
Render 'l' in Arial at (20, 0) size:12 color:blackconst forest = createForest();
console.log(`Trees planted: ${forest.getTreeCount()}`);Trees planted: 1000
Tree types created: 3const forest = createForest();
console.log(`Trees planted: ${forest.getTreeCount()}`);
console.log(`Tree types: ${forest.getTreeTypeCount()}`);
console.log(forest.render().split('\n').slice(0, 3).join('\n'));Trees planted: 50
Tree types: 3
Oak tree (oak.png) at (234.5, 567.8) health:100% color:green
Pine tree (pine.png) at (123.4, 890.1) health:100% color:green
Birch tree (birch.png) at (456.7, 234.5) health:100% color:greenconst system = createParticleSystem();
console.log(`Particles: ${system.getParticleCount()}`);
console.log(`Particle types: ${system.getParticleTypeCount()}`);
system.update(); // Simulate one frame
console.log(system.render().split('\n').slice(0, 3).join('\n'));Particles: 30
Particle types: 9
float particle (dot.png) at (100.5, 99.8) color:red alpha:0.99
fall particle (dot.png) at (99.2, 100.7) color:blue alpha:0.99
sparkle particle (dot.png) at (100.1, 100.3) color:yellow alpha:0.99Concepts
Complexity Analysis
Implementation
text-document
// Flyweight implementation code here