Flyweight Design Pattern in Java
Flyweight saves memory by sharing objects that are the same, instead of creating thousands of copies.
Real life example
A game forest with 10,000 trees. All oak trees share one picture and only the position is different.
When to use
Your program needs a huge number of similar objects and memory is a problem.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeFactory.get("Oak").draw(1, 2);
TreeFactory.get("Oak").draw(5, 9); // same Oak object, only position changes
}
}
class TreeType { // shared data
private String name;
TreeType(String name) { this.name = name; }
void draw(int x, int y) { System.out.println(name + " at " + x + "," + y); }
}
class TreeFactory {
private static Map<String, TreeType> cache = new HashMap<>();
static TreeType get(String name) {
return cache.computeIfAbsent(name, TreeType::new); // reuse if it exists
}
}Output
Oak at 1,2
Oak at 5,9