Tutorial 7: Flyweights and Factories


Introduction

This tutorial covers:


Class Variable

Below is an UML diagram for the design of class Variable.

flyweight.png (18979 bytes)

The Flyweight Pattern

The flyweight pattern is a design pattern used to save space and in some cases time.   To save space, objects of certain type are stored in one place called a storage "pool".  These objects are called flyweights.  The flyweight pattern is used when objects need to be shared because there is expensive to have duplicate copies and/or because the construction of these objects are expensive.  For example, in a word processing application, there can be hundreds of thousands of "character" objects.  It is thus necessary to define a Character class with a minimal set of attributes and behaviors and share the Character objects.

A client cannot directly instantiate a flyweight but has to ask a flyweight "factory" to "vend" it one by calling an appropriate factory method.   A factory class is a class that is capable of manufacturing instances of objects of certain type.  As such, it has access to the constructors of the objects it can create.  When a flyweight factory is asked to vend a particular flyweight, it looks it up in the storage pool.  The flyweight object is returned if found, if not, the factory instantiates a new flyweight (it has access to the constructor!), adds it to the pool, and returns it to the calling client.  In general the factory maintains a reference to the storage pool to have quick access to it.  In some cases, the factory serves as the storage pool itself.  The high level specification for flyweights and its factory is "a flyweight factory has (access to) many flyweight objects".   Below is the general UML diagram describing the flyweight pattern.

flyPattern.png (6395 bytes)

 

D. X. Nguyen, Oct. 19, 1999.
Copyright 1999, all rights reserved.
dxnguyen@cs.rice.edu