Flyweight Pattern Explained with Java Code and Real-World Scenarios
This article introduces the Flyweight design pattern, explains its intrinsic and extrinsic state concepts, presents real-world use cases such as board games and text editors, and provides a complete Java implementation with an abstract piece, concrete piece, factory pool, and test demonstration, highlighting memory savings and potential pitfalls.
Flyweight Pattern Overview
Extract large amounts of repeated immutable data into shared objects stored in a pool, eliminating duplicate instance creation and reducing memory consumption.
Key Concepts
Intrinsic state : immutable, shareable data.
Extrinsic state : varies per use, supplied at runtime, not stored in the shared object.
Purpose: lower memory usage and improve performance by reusing objects.
Practical Scenarios
Go board pieces: two colors share a base object; coordinates are extrinsic.
Text editor: characters share font style, only position is recorded.
Other examples: e‑commerce SKU templates, game monster templates, icon caches.
Java Implementation (Go board example)
1. Abstract Flyweight
public abstract class ChessPiece {
// Intrinsic state: color (shared)
protected String color;
public ChessPiece(String color) {
this.color = color;
}
// Extrinsic state: coordinates x, y passed in
public abstract void show(int x, int y);
}2. Concrete Flyweight
public class WeiQi extends ChessPiece{
public WeiQi(String color) {
super(color);
}
@Override
public void show(int x, int y) {
System.out.println(color + "棋子,坐标:(" + x + "," + y + ")");
}
}3. Flyweight Factory (Object Pool)
import java.util.HashMap;
import java.util.Map;
public class ChessFactory {
private Map<String, ChessPiece> pool = new HashMap<>();
public ChessPiece getPiece(String color){
if(!pool.containsKey(color)){
pool.put(color, new WeiQi(color));
System.out.println("新建"+color+"棋子存入池子");
}
return pool.get(color);
}
public int getPoolSize(){
return pool.size();
}
}4. Test Usage
public class Test {
public static void main(String[] args) {
ChessFactory factory = new ChessFactory();
ChessPiece b1 = factory.getPiece("黑色");
b1.show(2,3);
ChessPiece b2 = factory.getPiece("黑色");
b2.show(5,6);
ChessPiece w1 = factory.getPiece("白色");
w1.show(1,1);
System.out.println("池子内实例总数:"+factory.getPoolSize());
}
}Common Business Scenarios
Programs that must create massive numbers of similar objects under heavy memory pressure.
Objects possess immutable shared attributes while only a few pieces of data vary per use.
Resource caches such as connection pools, icon pools, character style pools, product templates.
Games with large numbers of NPCs, bullets, or items reusing base templates.
Rich‑text editors rendering huge amounts of text, sharing font and size styles.
Pitfalls
If objects have little or no shareable intrinsic data, applying the Flyweight pattern adds unnecessary pool‑management complexity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
