Java
Usage examples: The Flyweight pattern has a single purpose: minimizing memory intake. If your program doesn’t struggle with a shortage of RAM, then you might just ignore this pattern for a while.
Examples of Flyweight in core Java libraries:
java.lang.Integer#valueOf(int)(alsoBoolean,Byte,Character,Short,LongandBigDecimal)
Identification: Flyweight can be recognized by a creation method that returns cached objects instead of creating new.
Rendering a forest
In this example, we’re going to render a forest (1.000.000 trees)! Each tree will be represented by its own object that has some state (coordinates, texture and so on). Although the program does its primary job, naturally, it consumes a lot of RAM.
The reason is simple: too many tree objects contain duplicate data (name, texture, color). That’s why we can apply the Flyweight pattern and store these values inside separate flyweight objects (the TreeType class). Now, instead of storing the same data in thousands of Tree objects, we’re going to reference one of the flyweight objects with a particular set of values.
The client code isn’t going to notice anything since the complexity of reusing flyweight objects is buried inside a flyweight factory.
trees
trees/Tree.java: Contains state unique for each tree
package refactoring_guru.flyweight.example.trees;
import java.awt.*;
public class Tree {
private int x;
private int y;
private TreeType type;
public Tree(int x, int y, TreeType type) {
this.x = x;
this.y = y;
this.type = type;
}
public void draw(Graphics g) {
type.draw(g, x, y);
}
}trees/TreeType.java: Contains state shared by several trees
trees/TreeFactory.java: Encapsulates complexity of flyweight creation
forest
forest/Forest.java: Forest, which we draw
Demo.java: Client code
OutputDemo.png: Screenshot

OutputDemo.txt: RAM usage stats
Last updated