FlyweightFactory: Once you have flyweight, then you can have a FlyweightFactory as a Flyweight Pool which is a collection of Flyweights that are cached to be shared. FlyweightFactory is usually a Singleton to keep track of whether a particular flyweight has been generated and returns either a new instance or reference to one that it has already generated.
- Apply Flylweight to cells on a big board. For example, each cell on a 1000 by 1000 game of life game board can be a flyweight object to reduce memory footprint for each cell since extrinsic state are kelp outside of the Flyweight object.
- The Java language specification requires that integers between -128 and 127 be 'cached' is actually a form of flyweight to conserve system resource.
flyweight code example
when to use
- Need use large numbers of objects when a simple repeated shared representation would save a large amount of memory.
- Not often used at the application level in Java, more of a system resource management technique that is used at a lower level than Java.
- Flyweight tends to go with composite that contains Flyweight objects.
Flyweight vs. Strategy
- Flyweights are small strategy classes handled by the flyweight factory.
- Both Strategy and Flyweight externalize extrinsic state.