Flyweight Factories and Object Pools
You'll learn how a factory manages flyweight objects to ensure only one instance exists per unique intrinsic state.
The Management Problem
You've learned that flyweight objects share intrinsic state to save memory. But how do you guarantee that objects with identical intrinsic state aren't accidentally duplicated? Enter the flyweight factory: a central manager that creates flyweights on demand and caches them for reuse.
How Flyweight Factories Work
Think of a factory like a library card catalog. When you request a book (flyweight object), the librarian (factory) checks if it's already in circulation. If yes, you get that existing copy. If no, the librarian orders it once and keeps track of it for future requests.
The factory maintains an object pool—a collection (like a dictionary or map) that stores already-created flyweights indexed by their intrinsic state. When a client requests a flyweight:
- The factory checks the pool using the intrinsic state as a key
- If found, it returns the existing instance
- If not found, it creates a new flyweight, adds it to the pool, and returns it
This ensures shared objects truly are shared—no duplicates waste memory.
Why This Matters
Without a factory, clients might accidentally create multiple identical flyweight objects, defeating the pattern's purpose. The factory enforces the "single instance per intrinsic state" rule automatically. The object pool acts as a reuse mechanism: objects are allocated once and retrieved many times, drastically reducing memory overhead when you have many similar objects.
Key Takeaway: A flyweight factory uses an object pool to guarantee that flyweights with identical intrinsic state are reused, not recreated, making the pattern both safe and efficient.