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.
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.
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.
This pattern is quite easy to create.
This pattern is quite easy to maintain.
This pattern is quite easy to remove too.
- Use pre-existing tools from the language like the sets in Java.