Structural Patterns  «Prev  Next»
Lesson 8 Flyweight: consequences
ObjectiveUnderstand the Tradeoffs of the Flyweight Pattern

Understand the Tradeoffs of the Flyweight Pattern

What are the consequences and tradeoffs of the Flyweight Pattern that a software architect must consider when designing software?
The main purpose of Flyweights is to save space (memory). Although performance/memory tradeoffs are a classic issue in program optimization, most of the time the impact on performance of using a Flyweight is negligible, especially if the objects are naturally immutable.
I have focused on immutable objects here, since they are definitely the simplest to work with and serve many purposes. However, even mutable objects can be represented by Flyweights if the mutable parts can be separated out and made extrinsic. For example, a drawing document might be required to store the position of each Flyweight shape rather than storing the position of the shape as part of the Shape class.
The disadvantage of this approach is that moving the state outside the object breaks encapsulation, and may be less efficient than keeping the state intrinsic. In these cases it may be necessary to decide whether performance or memory is more important.
Flyweights are based on pointers or references. Working with Flyweights is easy in a language like Java where all object variables are references and a garbage collector is responsible for removing old objects. Flyweights are just a little trickier in a language like C++ where objects can be allocated as local variables on the stack and destroyed as a result of programmer action.

Flyweight Pattern Described

A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used. A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally.