Avoid the overhead of large numbers of very similar classes with the Flyweight pattern. Learn how to recognize instances that are fundamentally the same except for a few parameters, move those variables outside the class instance, and pass them in as part of a method call.

This chapter is from the book

This chapter is from the book

The Flyweight pattern is used to avoid the overhead of large numbers of very
similar classes. 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 by sharing them.

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 that is passed in as arguments. The Flyweight is
appropriate for small, fine-grained classes like individual characters or icons
on the screen. For example, you might be drawing a series of icons on the screen
in a window, where each represents a person or data file as a folder, as shown
in Figure 19-1.

Figure 19-1. A set of folders representing information about various people.
Since these are so similar, they are candidates for the Flyweight pattern.

In this case, it does not make sense to have an individual class instance for
each folder 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 document 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. In this case
there only has to be one instance of each character, rather than one for each
appearance of that character.