🪶Flyweight Pattern – Overview
🧠 Concept
🧱 Key Roles
Role
Description
💻 Java Example – Drawing Trees in a Game
import java.util.*;
// ----- Flyweight -----
interface TreeType {
void draw(int x, int y);
}
// ----- Concrete Flyweight -----
class ConcreteTreeType implements TreeType {
private final String name; // intrinsic state
private final String color;
private final String texture;
public ConcreteTreeType(String name, String color, String texture) {
this.name = name;
this.color = color;
this.texture = texture;
}
@Override
public void draw(int x, int y) {
System.out.println("Drawing " + name + " tree (" + color + ", " + texture + ") at (" + x + "," + y + ")");
}
}
// ----- Flyweight Factory -----
class TreeFactory {
private static final Map<String, TreeType> treeTypes = new HashMap<>();
public static TreeType getTreeType(String name, String color, String texture) {
String key = name + color + texture;
treeTypes.putIfAbsent(key, new ConcreteTreeType(name, color, texture));
return treeTypes.get(key);
}
}
// ----- Context / Client -----
class Tree {
private final int x; // extrinsic state
private final int y;
private final TreeType type; // shared flyweight
public Tree(int x, int y, TreeType type) {
this.x = x;
this.y = y;
this.type = type;
}
public void draw() {
type.draw(x, y);
}
}
public class Main {
public static void main(String[] args) {
TreeType oakType = TreeFactory.getTreeType("Oak", "Green", "Rough");
TreeType pineType = TreeFactory.getTreeType("Pine", "DarkGreen", "Smooth");
List<Tree> forest = List.of(
new Tree(10, 20, oakType),
new Tree(15, 25, oakType),
new Tree(50, 60, pineType)
);
forest.forEach(Tree::draw);
}
}🧠 Flow Summary
Step
Action
Result
🪜 Summary
🧾 Real-world Analogy
🧭 TL;DR
Last updated