Flyweight Pattern

One of the Gang Of Four patterns.

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

The Flyweight Pattern describes how to support a large number of fine grained objects efficiently, by sharing commonalities in state. For example, when designing a word processor application, you might create an object for each character typed. Each Character object might contain information such as the font face, size and weight of each character. The problem here is that a lengthy document might contain tens of thousands of characters, and objects - quite a memory killer! The Flyweight pattern addresses the problem by creating a new object to store such information, which is shared by all characters with the same formatting. So, if I had a ten-thousand word document, with 800 characters in Bold Times-New-Roman, these 800 characters would contain a reference to a flyweight object that stores their common formatting information. The key here is that you only store the information once, so memory consumption is greatly reduced. -- Tobin Harris

The Flyweight pattern is often combined with the Composite Pattern (163) to implement a logically hierarchical structure in terms of a directed-acyclic graph with shared leaf nodes.

It's often best to implement State Pattern (305) and Strategy Pattern (315) objects as flyweights.



See original on c2.com