メモリ効率を高めるFlyweightパターン
細粒度のオブジェクトを共有し、最小限のメモリで多数のインスタンスを扱えるFlyweightパターンを学びます。
「メモリ効率を高めるFlyweightパターン」はCoddyKit上の無料Clean Architecture & Design Patterns in Practiceレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「メモリ効率を高めるFlyweightパターン」レッスンは無料ですか?
はい。「メモリ効率を高めるFlyweightパターン」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Clean Architecture & Design Patterns in Practiceコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Clean Architecture & Design Patterns in Practiceコースには全4レッスンが含まれています。
「メモリ効率を高めるFlyweightパターン」で何を学びますか?
細粒度のオブジェクトを共有し、最小限のメモリで多数のインスタンスを扱えるFlyweightパターンを学びます。 ブラウザで直接実行するハンズオンコードでClean Architecture & Design Patterns in Practiceを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Clean Architecture & Design Patterns in Practiceを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのClean Architecture & Design Patterns in Practiceは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「メモリ効率を高めるFlyweightパターン」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このClean Architecture & Design Patterns in Practiceレッスンでコードを書いて実行できますか?
はい。すべてのClean Architecture & Design Patterns in Practiceレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- AdapterとDecoratorパターン
- FacadeとProxyパターン
- CompositeとBridgeパターン
- メモリ効率を高めるFlyweightパターン