Repaso
Español
Design & PracticesAdvancedDP-51

The JVM caches Integer objects from -128 to 127 and reuses string literals from the string pool. Which pattern is this?

Options

  1. Flyweight: share common immutable objects instead of making copies (Correct option)
  2. Observer: objects get notified when another object changes state
  3. Command: each request is wrapped inside its own object
  4. Mediator: objects talk to each other through a central object

Answer

Flyweight: share common immutable objects instead of creating many identical ones

Why

Flyweight saves memory by sharing objects that are identical and immutable instead of creating duplicates.

Integer.valueOf(100) always returns the same cached object; identical string literals share one String in the pool.

It only works safely when the shared object is immutable.

Remember

Flyweight = share identical immutable objects.

Key terms

Practice this question in Repaso