Flyweight pattern objects are immutable?

472 views Asked by At

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?

2

There are 2 answers

0
Brian Agnew On

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.

0
jaco0646 On

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.