advancedFlyweight Pattern

Why must a shared flyweight object be immutable once it has been constructed?

A flyweight instance is deliberately referenced by many different objects at once -- that sharing is the entire point of the pattern. If any code were able to mutate a flyweight's fields after construction, every single object holding a reference to that shared instance would change at the same moment, silently, with no indication at the mutation's call site that it was affecting anything beyond the one object being touched directly. That makes immutability a hard requirement rather than a nice-to-have: without it, sharing state to save memory introduces a correctness bug that is extremely difficult to trace back to its source, since the bug manifests far away from where the actual mutation happened.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to When is it safe to share a single instance of a state class across multiple context objects, and when does that become a bug?← Back to all Low-Level Design & Design Patterns questions