🚀 𝐒𝐦𝐚𝐫𝐭 𝐌𝐞𝐦𝐨𝐫𝐲 𝐌𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐅𝐥𝐲𝐰𝐞𝐢𝐠𝐡𝐭 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 🚀
⁉️ 𝑴𝒐𝒕𝒊𝒗𝒂𝒕𝒊𝒐𝒏
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?