Flyweight Pattern

Role

The Flyweight pattern promotes an efficient way to share common information present in small objects that occur in a system in large numbers. It thus helps reduce storage requirements when many values are duplicated. The Flyweight pattern distinguishes between the intrinsic and extrinsic state of an object. The greatest savings in the Flyweight pattern occur when objects use both kinds of state but:

  • The intrinsic state can be shared on a wide scale, minimizing storage requirements.

  • The extrinsic state can be computed on the fly, trading computation for storage.

Illustration

Consider now the image aspect of the Photo Library application, as discussed with the Composite pattern. At any one time, we want to have a full page of images displayed and, with no discernable time lag, we want to be able to scroll up and down through the library. This implies that as many images as possible should be preloaded into memory and kept there while the photo application is running. For a Photo Group application, the primary function is to arrange photos in groups. Photos can belong to several different groups, so the number of images to display could increase enormously. If all of the images do not fit in memory, the fact that they can belong to different groups means that any given photo may be called up for display at irregular times, resulting in a lot of disk transfers.

Consider the illustration in Figure 3-3. With a smaller window, the first two groups could have scrolled ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.