180 likes | 404 Views
Flyweight An Object Structural Design Pattern. JM Imbrescia. Intent. “Use Sharing to support large numbers of fine-grained objects efficiently.” Simply put, a method for storing a small number of complex objects that are used repeatedly. Motivation (Why use the Flyweight Pattern?).
E N D
FlyweightAn Object Structural Design Pattern JM Imbrescia
Intent • “Use Sharing to support large numbers of fine-grained 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 • ConcreteFlyweight • UnsharedConcreeteFlyweight • FlyweightFactory • Client
Image from the book thanks to: http://www.cs.jhu.edu/~scott/oos/lectures/PatternDiagrams
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.