Tuesday, December 19, 2006

Flyweight Design Pattern

I was wondering about Flyweight pattern for so many days. Let me present its definition and some detail.

Flyweight pattern: Flyweight is one of the structural patterns. The Flyweight Design Pattern is useful when there is the need for many, many objects to exist that share some information. Several thousand or even several hundred thousand objects might be needed, and this is usually very memory-consuming to keep track of. Given certain constraints, it is possible to reduce this problem greatly and make the presence of so many objects possible. If all of the objects share some intrinsic, invariant information that is constant among all of them, it can be removed from each object, and referenced. This eliminates the redundancy of having to repeat the same invariant, intrinsic information for each object, so instead of storing the same information n times for n objects, it is only stored once. This object that contains all of the intrinsic information is called a flyweight object.
It is possible for a flyweight to have extrinsic information as well. This information must be stateless and determined by context, having no stored values, but values that can be calculated on the spot.
The different components involved in the Flyweight Pattern are the Flyweight, the ConcreteFlyweight, the FlyweightFactory and the Client.

One classic example of a flyweight pattern is the characters stored in a word processor. Each character represents an object that has a font face, font size, and other formatting data. As you can imagine, a large document with this data structure would bloat the memory footprint of the word processor. Moreover, since much of this data is repeated, there must be a way to reduce the footprint - the Flyweight pattern. Each of the character objects would contain a reference to a separate formatting object which contains the required properties. This greatly reduces the memory footprint by combining all of the like-formatted characters into simpler objects that reference a single formatting object.

In Design Patterns, the Gang of Four (GOF) authors describe the Flyweight pattern like this:

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

0 Comments:

Post a Comment

<< Home