THE FLYWEIGHT PATTERN
There are cases in programming where it seems that you need to
generate a very large number of small class instances to represent data.
Sometimes you can greatly reduce the number of different classes that you
need to instantiate if you can recognize that the instances are fundamentally
the same except for a few parameters. If you can move those variables outside
the class instance and pass them in as part of a method call, the number of
separate instances can be greatly reduced.
The Flyweight design pattern provides an approach for handling such
classes. It refers to the instance’s intrinsic data that makes the instance
unique, and the extrinsic data which is passed in as arguments. The Flyweight
is appropriate for small, fine-grained classes like individual characters or
icons on the screen. For example, if you are drawing a series of icons on the
screen in a folder window, where each represents a person or data file, it does
not make sense to have an individual class instance for each of them that
remembers the person’s name and the icon’s screen position. Typically these
icons are one of a few similar images and the position where they are drawn
is calculated dynamically based on the window’s size in any case.
In another example in Design Patterns, each character in a font is
represented as a single instance of a character class, but the positions where
the characters are drawn on the screen are kept as external data so that there
needs to be only one instance of each character, rather than one for each
appearance of that character.
Recent Comments