design-patternsflyweight-pattern

Flyweight pattern - What is the point of an unshared concrete instance?


As we all know, in the UML diagram of the Flyweight Pattern there is an unshared concrete instance, and it implements the interface flyweight. My question is, why should it implement it if its extrinsic state is kind of pointless? I mean, for the shared concrete instances, the interface is needed so you must be sure that the extrinsic state can be passed, but what about the unshared? Can we not easily not implement the interface and achieve the same results?


Solution

  • Extending Flyweight interface gives the opportunity to decouple the client from the flyweight pattern implementation.

    Example:

    There's a Flyweight pattern implemented for 'Glyph'-s. According to the UML of the pattern, 'Glyph' represents the 'Flyweight' base class or interface. 'Client' works with a set of glyphs. FlyweightFactory (here GlyphFactory) can create glyphs (typically SharedFlyWeightGlyph object instances) using the flyweight pattern.

    The Client probably stores a text as a set of glyphs.

    Now let's say, next to the normal glyphs, you want to use a few custom glyphs which can't be created by FlyWeightFactory. By extending 'Glyph' interface (which is the UnsharedFlyweight according to the UML diagram of the pattern) you have the chance to use custom glyphs, though, in these cases the performance benefit of the flyweight pattern can't be utilized.