javadesign-patternsflyweight-pattern

What is the difference between intrinsic and extrinsic state as described in Flyweight Pattern?


From the chapter on FlyWeight Pattern inside Gang of Four the FlyWeight pattern is applicable when most object state can be made extrinsic.

What does extrinsic state mean ? I get the feeling that this pattern is used for sharing of objects . If objects are to be shared , then how can that object even have any state at all ?


Solution

  • Whatever the specific wording in that bulleted list, it is important to understand the message: Flyweight applies to the case where an important part of state can be shared among many objects because it is some data that is the same for all of them. Typically the shared state is immutable by nature (i.e., "universal truth"). The example with font faces makes this quite clear; an example from everyday Java is java.util.regex.Pattern, the flyweight, vs. Matcher, the client object that reuses it and holds local extrinsic state. Many Matchers can exist in parallel, all reusing the compiled regex on the inside.

    This quote makes things clearer than the one from your question:

    The more flyweights are shared, the greater the storage savings. The savings increase with the amount of shared state. The greatest savings occur when the objects use substantial quantities of both intrinsic and extrinsic state, and the extrinsic state can be computed rather than stored. Then you save on storage in two ways: Sharing reduces the cost of intrinsic state, and you trade extrinsic state for computation time.