The Flyweight

Intent: Use sharing to support large numbers of fine-grained objects efficiently (Gamma et al., 1994).

Example: Font systems model each letter with a different class that is capable of scaling, micropositioning, kerning, and other (often heavyweight) behaviors. If a large document contains many examples of, say, the letter A, then creating an instance of A for each appearance would be wasteful since all A's would behave the same; the only difference would be their location (row and column, for example). The flyweight suggests pulling out the varying state position into lightweight objects, all of which defer to the single instance of the letter for all behaviors.

images

Figure 9: Flyweight example diagram.

Qualities and Principles: The flyweight is a quintessential example of the separation of concerns. The varying state is one concern; the consistent behavior is another. Clients couple only to the state object, never the behavior, whereas the state object couples to the abstraction of the behavior (Letter in the example). Any number of state objects can exist without requiring more behavior objects, eliminating redundant resource consumption.

Testing: The flyweight (CharPosition in the example) can easily be tested against a mock (see p. 38) of the behavioral object, making the test fast and narrowly focused.

Questions and Concerns: The flyweight increases delegation in the system to reduce resource consumption, but does create more use of the stack, the virtual access table (VAT), and other virtualization resources of the runtime. Thus, we sacrifice a bit of performance to avoid wasting memory.

The flyweight can be used to eliminate any manner of a client-specific state from coupling to any kind of behavior, thus whenever a heavyweight entity is created, the flyweight should be considered as a possibility. A good example of this is the facade (see p. 30).

The flyweight assumes that all reuse of the behavior object is consistent. If there are exceptions to this, an adapter (see p. 16) or proxy (see p. 46) can be used to resolve the differences. The behavior objects are often singletons (see p. 48) to enforce they are not created repeatedly.

For more information: https://tinyurl.com/y42bp2ru

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157