Flyweight pattern is a structural pattern in GoF as it supports large numbers of fine-grained objects efficiently. Since each fine-grained object (e.g. a character in an editor application) may incur overhead that adds up. This pattern shares objects in a pool (Flyweight Factory) to minimize memory use. source: GoF overviewFlyweight: A flyweight is a shared independent object with its own intrinsic state (e.g. character code) that is stateless or immutable. If the intrinsic state is not going to be modified, then the object can be shared. Flyweight objects are shared among different contexts that hold extrinsic states (e.g. coordinate position in the document and its typographic style). These extrinsic state (out side of object) of the context will be passed by client object to the flyweight to operate. A flyweight makes as much of its state information extrinsic as possible and that is where the memory saving comes from. 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. Real world Flyweight use cases:
flyweight code exampleFlyweightFactory class:
Flyweight class:
source: Java™ Design Patterns: A Tutorial when to use
comparisonFlyweight vs. Composite
Flyweight vs. Strategy
references
0 Comments
Leave a Reply. |
Categories
All
Archives
May 2020
|