What is the difference between intrinsic and extri

2020-02-28 06:46发布

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 ?

3条回答
淡お忘
2楼-- · 2020-02-28 07:00

extrinsic - state that belongs to the context of the object (external) or unique to that instance

intrinsic - state that naturally belongs to the 'FlyWeight' object and thus should be permanent or immutable (internal) or context free.

查看更多
forever°为你锁心
3楼-- · 2020-02-28 07:01

Let's take an example of a Word processor:

A Word processor deals with Character objects. The state of Character objects is the character content, the font, style,location etc (as far as the Word processor is concerned). Different documents use different instances of a character. Assuming we are just dealing with a-z chars, different documents use letters from a-z pool but might apply a different font/style. So, if we separate the content of the character from the font/style we can share these characters and this makes sense because the total different types of characters are less (26 in our case but a constant otherwise) compared to different instances of characters used in different documents. Sharing these character instances would mean to share the Character instances content wise and apply context like font/style externally to these characters. Character content is intrinsic state and font/style is extrinsic state. Separating state into intrinsic and extrinsic states led to huge storage savings in the above example.

查看更多
男人必须洒脱
4楼-- · 2020-02-28 07:05

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 data can be shared among many objects because it is immutable. The example with font faces makes this quite clear; an example from everyday Java is java.util.regex.Pattern, the holder of immutable extrinsic state, vs. Matcher, the flyweight that reuses it and holds local intrinsic 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.

查看更多
登录 后发表回答