Flyweight Pattern
Bryan Hansen
twitter: bh5k | [Link]
Concepts
▪ More efficient use of memory
▪ Large number of similar objects
▪ Immutable
▪ Most of the object states can be extrinsic
▪ Examples:
▪ [Link]
▪ [Link]#valueOf(int)
▪ Boolean, Byte, Character, Short, Long
Design
Pattern of patterns
Utilizes a Factory
Encompasses Creation and Structure
Client, Factory, Flyweight, ConcreteFlyweight
UML
Everyday Example - Integer
Integer firstInt = [Link](5);
Integer secondInt = [Link](5);
Integer thirdInt = [Link](10);
[Link]([Link](firstInt));
[Link]([Link](secondInt));
[Link]([Link](thirdInt));
Exercise Flyweight
Inventory Management System
Client, Catalog, Order, Item
Pitfalls
▪ Complex pattern
▪ Premature optimization
▪ Must understand Factory
▪ Not a graphical pattern
Contrast
Flyweight Facade
▪ Memory Optimization ▪ Refactoring Pattern
▪ Optimization Pattern ▪ Simplified Client
▪ Immutable Objects ▪ Provides a different interface
Flyweight Summary
• Great for Memory Management
• A little bit complex
• Used a lot by the core API