Referral in the Flyweight project standard

5

There's one thing in the Desing Flyweight Pattern that's making me really confused. Briefly, the standard says that to save memory in a situation where you use several similar objects, you use a factory that returns references to the same object in a flyweights pool instead of instantiating thousands of different objects.

I also saw that to generate data independence between each object, it is necessary to understand two concepts in this pattern: extrinsic and intrinsic data, which I also did not understand very well.

If using this pattern I am using references to the same object, will not have problems when changing the state of only one object and end up changing the state of all? For example: I have developed a game in which, using this pattern, I have the object port that is shared between all the "ports" of the game; the player controls a character that can open or close doors. If all doors in the game are referencing a same object, the game will not have the bug of when the character opens a door, inexplicably all the doors in the same scenario open?

I saw that this problem could be solved with the concept of extrinsic and intrinsic data, but in all the examples I read, I did not understand how this is implemented. How, really, is a state of state independence implemented between various flyweights?

    
asked by anonymous 14.03.2014 / 05:08

1 answer

4

I do not know if these terms "intrinsic" and "extrinsic" have a connotation t ecnica in this context or if they are only part of the explanation of the chapter but there is nothing magical about it. In the end, if you want to use the optimization described by the flyweight standard, the shared objects need to be immutable or you will encounter those problems that you are imagining. If you need to have some changeable property that is not to be shared it needs to be stored in a separate object than the shared part.

For example, suppose your ports have two properties: the image used to represent it and the open state (open / closed). The state will have to be an instance variable stored separately for each port object but the images are immutable and can be cached and shared, as in the flyweight pattern.

    
14.03.2014 / 09:31