0Pricing
Clean Architecture & Design Patterns in Practice · Lección

Patrón Flyweight para optimizar la memoria

Descubra el patrón Flyweight, que comparte objetos pequeños para admitir un gran número de instancias usando la mínima memoria posible.

Patrón Flyweight para optimizar la memoria es una lección gratuita de Clean Architecture & Design Patterns in Practice en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Clean Architecture & Design Patterns in Practice, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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.

Preguntas frecuentes

¿La lección «Patrón Flyweight para optimizar la memoria» es gratis?

Sí — el texto completo de «Patrón Flyweight para optimizar la memoria» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Clean Architecture & Design Patterns in Practice, actualiza a CoddyKit PRO. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.

¿Qué aprenderé en «Patrón Flyweight para optimizar la memoria»?

Descubra el patrón Flyweight, que comparte objetos pequeños para admitir un gran número de instancias usando la mínima memoria posible. Practicas Clean Architecture & Design Patterns in Practice con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Clean Architecture & Design Patterns in Practice?

No se requiere experiencia previa. Clean Architecture & Design Patterns in Practice en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Patrón Flyweight para optimizar la memoria»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Clean Architecture & Design Patterns in Practice?

Sí. Cada lección de Clean Architecture & Design Patterns in Practice incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Patrones Adapter y Decorator
  2. Patrones Facade y Proxy
  3. Patrones Composite y Bridge
  4. Patrón Flyweight para optimizar la memoria
← Volver a Clean Architecture & Design Patterns in Practice