Structural Patterns  «Prev  Next»
Lesson 6 Flyweight: applicability
Objective Learn when and when not to use the Flyweight pattern.

Flyweight Suitability and Applicability

The Flyweight pattern is useful for systems in which all of the following four conditions apply.

Quantity of objects used makes the system unwieldy

Poor environments also keel over when too many classes are used at once, but the Flyweight pattern does not solve this problem. When faced with this problem you may want to consider whether some of your different classes are really just instances of some common superclass.

The number of objects actually constructed is much smaller than the total possible objects

If the number of possible objects or the number of objects actually constructed is of the same order of magnitude or even larger than the actual number of objects, the Flyweight pattern does not help much. It only helps when there are many almost identical copies of the same small set of objects.

The objects can be made immutable

Since one object must stand in for many different objects, it should not change frequently. When a Flyweight object's state changes, the state of all the objects the Flyweight is representing changes. This is rarely what you want. If objects are not naturally immutable, you may be able to move the mutable parts outside of the object into the document or object that contains the Flyweights.

Objects do not need to be tested for identity

An identity test decides whether two objects are the same object. An equality test decides whether two objects have the same state.
For example, if a checking account and a savings account each have a $1000.00 balance, the balances are equal, but they are not the same balance. In Java == tests for identity while the equals() method tests for equality. However, Flyweights substitute the same identical object for objects that would otherwise be merely equal, so identity tests are not valid.