The Flyweight Design Pattern
The Flyweight design pattern can be summarized in three (3) words – minimize and share. In fact, I would label it as “minimize-and-share”. It makes it easier to remember and relate to the actual solution.
There are many ways to implement this as long as you minimize the creation of objects and share (or reuse) them in codes.
A classical example usage of this 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 that is easier to make the idea grasp is where we have a Software Development team with the following members.
- A Software Architect
- Two Senior Software Engineers
- A Senior QA Engineer
- A Senior UX Designer
- Two Software Testers
For this example, this team operates optimally and does not require additional members. Also for the management, the cost of maintaining their operation is pretty much fixed and within the budget.
In summary, we have only seven (7) bright and talented people who, as a team, may work on more than one project.
In a programming perspective, we have only seven (7) objects that can be reused. Memory usage is kept to the minimum.
Yet Another Example
You may heard of Java’s interning. Generally, it is a way to reuse String objects from the String Pool. Please check out my another post Java – Beyond String Pool.