Design Patterns

Flyweight



Design Pattern Type: Structural

GoF Statement of Intent:


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



A flyweight object is one that minimizes memory use by sharing as much data as possible with other similar objects. It is a way to use a large number of objects when a simple repeated representation would use up too much memory. One example is the representation of characters in a word processor. Each character must have a glyph (representation of the letter), a font, font metrics, and other formatting data. To repeat all of this for each character would take hundreds or thousands of bytes per character, but a flyweight defining the position of a character with references to the appropriate font, etc. would take far less memory.
UML Diagram:

Discussion and In-class Example:

Suppose you are writing a landscape design application. In this application a "design" may contain many tree objects. But, they don't do much. They have an XY location and draw themselves based on their size/age.


The problem you may find is that after creating a design with large groves of trees the application starts to run very slowly because it is having to handle thousands of tree objects. The solution is to create a single tree object and a separate tree manager.


Advantages of using the Flyweight
  1. Reduces the number of instances of an object, saving memory.
  2. Centralizes the state of many “virtual” objects into a single location (the manager).
  3. Used when a class has many instances all of which can be controlled identically.

The main problem with using a Flyweight, however is that single instances of objects cannot behave independently.