๐ ๐๐ฆ๐๐ซ๐ญ ๐๐๐ฆ๐จ๐ซ๐ฒ ๐๐๐ง๐๐ ๐๐ฆ๐๐ง๐ญ ๐ฐ๐ข๐ญ๐ก ๐ญ๐ก๐ ๐ ๐ฅ๐ฒ๐ฐ๐๐ข๐ ๐ก๐ญ ๐๐๐ญ๐ญ๐๐ซ๐ง ๐
โ๏ธ ๐ด๐๐๐๐๐๐๐๐๐
The intent of flyweight is to share an object instead of having many objects.
๐ ๐น๐๐๐-๐พ๐๐๐๐
๐บ๐๐๐๐๐๐๐
Assume you want to design a document editor, and this editor contains:
โข ๐ Tables
โข ๐ผ๏ธ Figures
โข ๐ค Characters
In object-oriented design, we usually represent these entities as objects.
โ ๏ธ But here's the problem:
Documents can contain thousands of characters, and creating a separate object for each one leads to:
๐ป Too many objects
๐ป High memory usage
๐ป Unacceptable run-time overhead
๐ก This is where the Flyweight Pattern becomes useful โ it helps avoid the cost of creating tons of similar objects by sharing them efficiently.
๐ฏ ๐๐จ๐ฅ๐ฎ๐ญ๐ข๐จ๐ง โ ๐
๐๐๐๐๐๐๐๐ ๐๐๐ญ๐ญ๐๐ซ๐ง
Flyweight is an object which can be shared in multiple contexts simultaneously.
๐ Flyweights cannot guess the context they operate in, so the client must pass the extrinsic state when needed.
๐ง The key idea lies in the difference between:
๐ธ Intrinsic state: stored inside the flyweight โ it's independent of the context and sharable.
๐ธ Extrinsic state: provided by the client โ it's context-dependent and cannot be shared.
๐ Example:
The character 'A' in a document is an intrinsic part โ the alphabet symbol stays the same.
But the font size, color, and position are extrinsic, as they vary by context.
๐ง ๐๐ฉ๐ฉ๐ฅ๐ฒ ๐
๐ฅ๐ฒ๐๐๐ข๐ ๐ก๐ญ ๐ฐ๐ก๐๐ง ๐๐ฅ๐ฅ ๐จ๐ ๐ญ๐ก๐ ๐๐จ๐ฅ๐ฅ๐จ๐ฐ๐ข๐ง๐ ๐๐ซ๐ ๐ญ๐ซ๐ฎ๐:
โ
A program uses a lot of objects.
โ
Storage costs are high due to the sheer quantity of objects.
โ
Most object state can be made extrinsic.
โ
Removing extrinsic state allows many objects to be replaced with fewer shared ones.
โ
The application does not rely on object identity. Identity check may return true even if the instances of flyweight are different conceptually. (e.g., font, size, color).
๐ ๐น๐๐๐๐๐๐
๐ท๐๐๐๐๐๐๐:
โพ ๐๐จ๐ฆ๐ฉ๐จ๐ฌ๐ข๐ญ๐: The Flyweight pattern is often combined with the Composite pattern to implement a logically hierarchical structure in terms of a directed-acyclic graph with shared leaf nodes.
โพIt's often best to implement ๐๐ญ๐๐ญ๐ and ๐๐ญ๐ซ๐๐ญ๐๐ ๐ฒ objects as flyweights.
๐ ๐๐จ๐๐ ๐๐ฑ๐๐ฆ๐ฉ๐ฅ๐
๐ GitHub - https://github.com/shirin-monzavi/FlyWeightDesignPattern
โHave you ever used the ๐ ๐๐๐๐๐๐๐๐ Pattern in your projects?
Top comments (0)