Padrão Flyweight para eficiência de memória
Descubra o padrão Flyweight, que compartilha objetos detalhados para comportar grandes quantidades de instâncias usando o mínimo de memória.
Padrão Flyweight para eficiência de memória é uma aula grátis de Clean Architecture & Design Patterns in Practice no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Clean Architecture & Design Patterns in Practice, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Clean Architecture & Design Patterns in Practice inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “Padrão Flyweight para eficiência de memória” é grátis?
Sim — o texto completo de “Padrão Flyweight para eficiência de memória” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Clean Architecture & Design Patterns in Practice, atualize para CoddyKit PRO. O curso de Clean Architecture & Design Patterns in Practice inclui 4 aulas no total.
O que vou aprender em “Padrão Flyweight para eficiência de memória”?
Descubra o padrão Flyweight, que compartilha objetos detalhados para comportar grandes quantidades de instâncias usando o mínimo de memória. Você pratica Clean Architecture & Design Patterns in Practice com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Clean Architecture & Design Patterns in Practice?
Nenhuma experiência prévia é necessária. Clean Architecture & Design Patterns in Practice no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Padrão Flyweight para eficiência de memória”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Clean Architecture & Design Patterns in Practice?
Sim. Cada aula de Clean Architecture & Design Patterns in Practice inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Padrões Adaptador e Decorador
- Padrões Fachada e Proxy
- Padrões Composto e Ponte
- Padrão Flyweight para eficiência de memória