Computer Science Design Patterns/Flyweight

{{Computer Science Design Patterns/Page It is a mechanism by which you can avoid creating a large number of object instances to represent the entire system. To decide if some part of a program is a candidate for using Flyweights, consider whether it is possible to remove some data from the class and make it extrinsic.
 * mode={{{mode|reading}}}
 * page={{{page|{{SUBPAGENAME}}}}}
 * stage=25
 * stage date=4 Mar, 2014
 * stage comment=Add more illustrations.
 * previous=Factory method
 * next=Interpreter
 * content=

Examples
A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning. In video games, it is usual that you have to display the same sprite (i.e. an image of an item of the game) several times. It would highly use the CPU and the memory if each sprite was a different object. So the sprite is created once and then is rendered at different locations in the screen. This problem can be solved using the flyweight pattern. The object that renders the sprite is a flyweight.

Cost
There are several implementations for this pattern. So it's up to you to find a cheap implementation. Only implement this pattern if you have or will have CPU or memory issues.

Creation
This pattern is quite easy to create.

Maintenance
This pattern is quite easy to maintain.

Removal
This pattern is quite easy to remove too.

Advises

 * Use pre-existing tools from the language like the sets in Java.

Implementations
The following programs illustrate the document example given above: the flyweights are called FontData in the Java example. The examples illustrate the flyweight pattern used to reduce memory by loading only the data necessary to perform some immediate task from a large Font object into a much smaller FontData (flyweight) object.

}}