享元模式与内存效率
了解享元模式如何共享细粒度对象,以极少的内存支持大量实例
享元模式与内存效率 是 CoddyKit 上的免费 Clean Architecture & Design Patterns in Practice 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clean Architecture & Design Patterns in Practice 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Memory Problem
Some applications must hold huge numbers of similar objects: characters in a document, tiles in a game, particles in a simulation.
Naively creating one full object per element can exhaust memory. The Flyweight pattern attacks this directly.
Core Idea: Share What Repeats
Flyweight splits an object state into two parts:
- Intrinsic state: shared, context-independent (e.g. a glyph shape).
- Extrinsic state: unique per use, passed in from outside (e.g. position).
Only the intrinsic part is stored once and reused.
A Concrete Scenario
Imagine rendering thousands of trees in a forest. Every tree of the same species shares the same texture and mesh.
Storing that texture once and reusing it across all instances is the essence of Flyweight.
The Flyweight Class
The flyweight holds only intrinsic, shareable data.
class TreeType {
final String name;
final String texture;
TreeType(String name, String texture) {
this.name = name;
this.texture = texture;
}
}The Flyweight Factory
A factory ensures flyweights are created once and reused, returning the existing instance when possible.
class TreeTypeFactory {
private static final Map<String, TreeType> pool = new HashMap<>();
static TreeType get(String name, String tex) {
return pool.computeIfAbsent(name, k -> new TreeType(name, tex));
}
}Passing Extrinsic State
The context object stores only the unique data and references the shared flyweight.
class Tree {
final int x, y;
final TreeType type;
Tree(int x, int y, TreeType type) {
this.x = x; this.y = y; this.type = type;
}
}Putting It Together
Thousands of Tree objects share a handful of TreeType flyweights.
public static void main(String[] args) {
java.util.List<Tree> forest = new java.util.ArrayList<>();
for (int i = 0; i < 100000; i++) {
TreeType t = TreeTypeFactory.get("Oak", "oak.png");
forest.add(new Tree(i, i, t));
}
System.out.println("Trees: " + forest.size());
}Intrinsic vs Extrinsic Discipline
The pattern only works if intrinsic state is truly immutable and shared. If you mutate a flyweight, every context using it is affected.
Always make flyweight fields final.
Relationship to Other Patterns
- The factory in Flyweight resembles an Object Pool, but pool objects are checked out exclusively while flyweights are shared concurrently.
- Flyweights are often combined with Composite for tree-like shared structures.
When to Use It
Reach for Flyweight when:
- You have a very large number of objects.
- Storage cost is high due to repeated state.
- That repeated state can be cleanly separated as intrinsic.
If object counts are modest, the indirection is not worth it.
Trade-offs
Flyweight trades CPU and complexity for memory. Passing extrinsic state on each call and looking up shared instances adds overhead. Use it only when memory is the real bottleneck.
Quick Check
Test your understanding of the Flyweight pattern.
Recap
You learned the Flyweight structural pattern.
- Split state into intrinsic (shared) and extrinsic (per-use).
- A factory reuses shared flyweights.
- It trades CPU for large memory savings when instance counts are huge.
常见问题解答
「享元模式与内存效率」课时是免费的吗?
是的 — 「享元模式与内存效率」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clean Architecture & Design Patterns in Practice 课程的其余内容,请升级到 CoddyKit PRO。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。
「享元模式与内存效率」这节课中我会学到什么?
了解享元模式如何共享细粒度对象,以极少的内存支持大量实例 你通过在浏览器中直接运行的动手代码来练习 Clean Architecture & Design Patterns in Practice,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Clean Architecture & Design Patterns in Practice 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Clean Architecture & Design Patterns in Practice 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「享元模式与内存效率」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Clean Architecture & Design Patterns in Practice 课中编写并运行代码吗?
能。每节 Clean Architecture & Design Patterns in Practice 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。