| ▲ | KPGv2 2 days ago | |
> which always creates a shallow copy of the book instance properties, thus nullifying any benefits of the flyweight pattern No, the opposite: it highlights the benefits of the flyweight pattern. The shallow copy saves memory. That's the point. You have two identical books. Rather than wasting memory with a deep copy, you make a shallow copy, where all your props point to locations in memory where values are located, and then you modify whatever is different. Now your shallow copy only consumes a small bit of extra memory. And if those props are all primitives, then you can then modify that shallow copy, and it won't affect the original. | ||
| ▲ | HumanOstrich 2 days ago | parent [-] | |
The point is to not make a copy at all for the shared data of the same book. That's even what the page claims is happening (but it's wrong). That's the whole point of the flyweight pattern[1]. Instead, the example returns the same book instance for the same isbn in `createBook`, then blindly copies the shared data like title, author, and isbn every time in `addBook` to a new object. > The shallow copy saves memory.... Versus not making a copy? A shallow copy of primitives still copies them and uses additional memory. Maybe there's some low-level optimization that makes it more efficient than that, but it's not relevant here. And there isn't any deep cloning happening in the example. Might as well get rid of the complexity and instantiate a new Book class every time. And maybe stop shallow-copying class instances into new plain objects. It works for the example but has footguns. Conveniently, there are other patterns on the site that would help you avoid creating an amalgamation of random merged class instances and objects. The whole example is a mess. | ||