Pattern Flyweight untuk Efisiensi Memori
Temukan pattern Flyweight yang berbagi objek berukuran kecil untuk mendukung banyak instans dengan penggunaan memori minimal.
Pattern Flyweight untuk Efisiensi Memori adalah pelajaran Clean Architecture & Design Patterns in Practice gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Clean Architecture & Design Patterns in Practice, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Clean Architecture & Design Patterns in Practice mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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.
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Pattern Flyweight untuk Efisiensi Memori” gratis?
Ya — teks lengkap “Pattern Flyweight untuk Efisiensi Memori” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Clean Architecture & Design Patterns in Practice, upgrade ke CoddyKit PRO. Kursus Clean Architecture & Design Patterns in Practice mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Pattern Flyweight untuk Efisiensi Memori”?
Temukan pattern Flyweight yang berbagi objek berukuran kecil untuk mendukung banyak instans dengan penggunaan memori minimal. Kamu berlatih Clean Architecture & Design Patterns in Practice dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai Clean Architecture & Design Patterns in Practice?
Tidak diperlukan pengalaman sebelumnya. Clean Architecture & Design Patterns in Practice di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Pattern Flyweight untuk Efisiensi Memori” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran Clean Architecture & Design Patterns in Practice ini?
Ya. Setiap pelajaran Clean Architecture & Design Patterns in Practice menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Pola Adaptor dan Penghias
- Pola Fasad dan Proksi
- Pola Komposit dan Jembatan
- Pattern Flyweight untuk Efisiensi Memori