Flyweight An Object Structural Design Pattern JM Imbrescia
Flyweight An Object Structural Design Pattern JM Imbrescia
Intent • “Use Sharing to • support large numbers of finegrained objects efficiently. ” Simply put, a method for storing a small number of complex objects that are used repeatedly.
Motivation (Why use the Flyweight Pattern? ) • If you have an application that would benefit from using objects throughout your design. – Document Editors – 50 Decks of cards
Definitions • Flyweight – A shared object that can be used in multiple contexts simultaneously. • Intrinsic – State information that is independent of the flyweights context. Shareable Information. • Extrinsic – State information that depends on the context of the flyweight and cannot be shared.
Applicability • Use the Flyweight when all of the following are true: – Application has a large number of objects. – Storage costs are high because of the large quantity of objects. – Most object state can be made extrinsic. – Many groups of objects may be replaced by relatively few once you remove their extrinsic state. – The application doesn’t depend on object identity.
Participants • Flyweight • Concrete. Flyweight • Unshared. Concreete. Flyweight • Flyweight. Factory • Client
Image from the book thanks to: http: //www. cs. jhu. edu/~scott/oos/lectures/Pattern. Diagrams
Consequences • Flyweights introduce runtime costs, these costs need to be offset by storage space savings. Savings come from: – Fewer total instances due to sharing. – Increasing intrinsic space per object. – Computing extrinsic state instead of storing it.
Related Patterns • Often combined with the Composite pattern. • State and Strategy objects are often implemented as flyweights.
- Slides: 9