• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All
  • About
Design Patterns | Flyweight
  1. References
  2. Example
    • The Flyweight
    • The Factory
    • A simple class to test the Flyweight design pattern

  1. References
    • Definition: (source: http://en.wikipedia.org/wiki/Flyweight_pattern)

      A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
  2. Example
    • The Flyweight:

      public class Entity {
          private final String id;
      
          public Entity(final String id) {
              this.id = id;
          }
      
          public String getId() {
              return id;
          }
      }

    • The Factory:

      public class EntityFactory {
          private static final Map<String, Entity> entities = new HashMap<String, Entity>();
      
          public static Entity getEntity(final String id) {
              final Entity entity;
      
              if (entities.containsKey(id)) {
                  entity = entities.get(id);
              } else {
                  entity = new Entity(id);
                  entities.put(id, entity);
              }
      
              return entity;
          }
      }

    • A simple class to test the Flyweight design pattern:

      public class FlyweightPatternTest {
          public static void main(String[] args) {
              Entity entity11 = EntityFactory.getEntity("1");
              Entity entity12 = EntityFactory.getEntity("1");
      
              System.out.println(entity11.equals(entity12));
          }
      }

© 2025  mtitek