We know , Java intern string pool is based on Flyweight design pattern. Also the String object is immutable. Is it compulsary that all the objects which are using Flyweight pattern is Immutable? . What is the difference between mutable and immutable objects in Flyweight pattern?
-
Because objects might be shared between thread. So to avoid any concurrent modification you must have immutable object. Maybe there are others reason but it's the main reason I can think of. – JEY Feb 13 '19 at 12:23
-
I [disagree](https://stackoverflow.com/a/52900564/1371329) that Java's String pool is based on the Flyweight Pattern. – jaco0646 Feb 13 '19 at 14:59
2 Answers
Is it compulsary that all the objects which are using Flyweight pattern is Immutable
You can implement something that looks like a flyweight, but your objects could well be mutable. I'd regard that as a poor implementation.
See the comments re. invariant state here.
Immutability is certainly desirable, just by the nature of the flyweight pattern's usage. Your clients may not be aware that the object they've requested/created is in fact shared with other components or threads, and having a mutable object in that scenario could well be problematic.

- 268,207
- 37
- 334
- 440
Remember the GoF Design Patterns were collected from code written around the 1980s. Mutability was not the concern it is today. With that in mind, all of their patterns support mutable state. The single note in the GoF book regarding mutability is a passing reference to deleting Composite leaf nodes. I would interpret all other object references in the book as potentially mutable.
That does not mean mutability is desirable, or that patterns cannot be immutable. Indeed, immutability is a great feature to be applied in design patterns for all the same reasons it is great elsewhere. But it's never compulsory in the GoF.

- 15,303
- 7
- 59
- 83