The Flyweight design pattern solves problems like:
How can large numbers of fine-grained objects
be supported efficiently?
See Applicability section for all problems Flyweight can solve.
See Solution section for how Flyweight solves the problems.
-
A naive way to support large numbers of objects
in an application is to create an object each time
it is needed.
-
For example, text editing applications.
To represent a text document at the finest levels,
an object is needed for every occurrence of a
character in the document, which can result in a huge
amount of objects.
"Even moderate-sized documents may
require hundreds of thousands of
character objects, which will consume lots of memory
and may incur unacceptable run-time overhead."
[GoF, p195]
-
That's the kind of approach to avoid
if we want to support large numbers of objects
efficiently.
-
It should be possible
to reduce the number of
physically
created objects.
Logically, there should be an object for every
occurrence of a character in the document.
-
For example, language processing and translation applications.
It should be possible to process any size of documents
efficiently.