Flyweight Pattern

The Flyweight pattern is a design pattern used in computer programming that falls under the category of Structural Patterns as defined by the Gang of Four (GoF) in their seminal book "Design Patterns: Elements of Reusable Object-Oriented Software". It is named after the boxing weight class that includes fighters who are less than 112lb, indicating the low memory footprint characteristic of this pattern.

The main goal of the Flyweight pattern is to minimize memory usage or computational expense by sharing as much data as possible with other similar objects. It's especially useful when a program needs to create a large number of objects of a class, which are similar in nature, but each object requires some kind of unique or independent data.

The pattern includes the following components:

  1. Flyweight: This is an interface that defines the methods that flyweights need to support.

  2. ConcreteFlyweight: This class implements the Flyweight interface and is able to store intrinsic (shared) state. Concrete flyweights need to be sharable and capable of manipulating their state that's passed as extrinsic (external, independent).

  3. FlyweightFactory: This is a class responsible for creating and managing flyweight objects. It ensures that flyweights are shared properly. When a client requests a flyweight, the FlyweightFactory supplies an existing instance or creates one, if none exists.

  4. Client: The client maintains references to flyweights and computes or stores the extrinsic state of flyweights.

In other words, a Flyweight pattern contains a Flyweight object that stores common states (intrinsic states) shared among all the original objects, and when a new object needs to be created, it uses the intrinsic data from the Flyweight object, and only adds the extrinsic data that are unique to it.

It's important to note that this pattern should be used only when the cost of creating an object is high (in terms of system resources) and the application uses a large number of objects which causes a significant memory footprint. Flyweight pattern is often used in conjunction with the Composite pattern to represent a hierarchical structure as a graph with shared leaf nodes.

A classic example of the Flyweight pattern in action is in the representation of text documents. Instead of having each character as a separate object with its own font and formatting information, the document can store a single object for each unique combination of character properties (a flyweight), with the actual characters in the document simply referencing these flyweight objects. This can dramatically reduce the memory used by the document, particularly for large documents that use a limited number of unique character styles.