开发者

Flyweight pattern - how to store flyweights in the data structure?

Classic Flyweight pattern implementation example from GoF book only stores character code in sharable "Characters" and uses "GlyphContext" to store extrinsic state in a tree structure. This example also mentions Rows and Columns, however it doesn't mention how would one store 开发者_JAVA百科a "collection" of flyweights ("Character" objects).

It's clear that this pattern allows to avoid creating huge number of objects by sharing instances, but how can one create a structure of such objects (for example, to represent a document) without creating a structure of references to cached objects (which would invalidate the purpose of the pattern)? I see that other examples use cached instances as "throw-away" objects, without building any sort of structure, but this doesn't seem to make any sense, since it could be replaced by a set of static operations.

Is it correct to conclude that if one needs to refer to flyweights after they are created, the benefit of the pattern can roughly be calculated as [size of intrinsic state]/[size of object reference]. This means that flyweight with only 1 field doesn't make sense?

EDIT: I was wrong in my "memory calculations"... Without flyweights, you need to store references anyway, but with flyweights, you don't need to store objects anymore. The basic point of the question still seems to be valid - the extent of savings, provided by the pattern is proportional to the size of intrinsic state, not the number of "logical objects". True or false?


Yes, even one field flyweight object makes sense if you will use that object a lot. Its faster to get their instances, then making new objects.

I find Map <string name, Object yourobject> (in Java) a good way to store them. Why you need "no structure"?

Using some structure to store flywieght being in use doesn't invalidate the purpose of the pattern. You need some instances of flywieghts to use them. You can make them during runtime and add them to list of them (that's the way it should be done, to avoid unneeded objects), or you can prepare them before runtime (witch makes "low" sense).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜