Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

README.md

Flyweight

Intent

Use sharing to support large numbers of fine-grained objects efficiently.

Applicability

The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all of the following are true:

  • An application uses a large number of objects
  • Storage costs are high because of the sheer quantity of objects
  • Most objects state can be made extrinsic
  • Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed
  • The application doesn't need object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects

Participants

  • Flyweight
    • declares an interface through which flyweights can receive and act on extrinsic state
  • ConcreteFlyweight (Character)
    • implements the Flyweight interface and adds storage for intrinsic state, if any. A ConcreteFlyweight object must be shareable. Any state it stores must be intrinsic; that is, it must be independent of the ConcreteFlyweight object's context
  • UnsharedConcreteFlyweight (Row, Column)
    • not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing; it doesn't enforce it. It's common for UnsharedConcreteFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure (as the Row and Column classes have)
  • FlyweightFactory
    • creates and manages flyweight objects
    • ensures that flyweights are shared properly. When a client requests a flyweight, the FlyweightFactory object supplies an existing instance or creates one, if none exists
  • Client
    • maintains a reference to flyweight(s)
    • computes or stores the extrinsic state of flyweight(s)

Related Patterns

The Flyweight pattern is often combined with the Composite pattern to implement a logically hierarchical structure in terms of a directed-acyclic graph with shared leaf nodes.
It's often best to implement State and Strategy objects as flyweights.
Look-up time in this scheme is proportional to the font change frequency. Worst-case performance occurs when a font change occurs in every character, but that's unusual in practice.
In the Sample Code given earlier, style information is made extrinsic, leaving the character code as the only intrinsic state.
See Abstract Factory for another approach to look-and-feel independence.