DEV Community

Cover image for Composite Design Pattern In C#
Shirin Monzavi
Shirin Monzavi

Posted on

Composite Design Pattern In C#

🚀 Design Pattern

⁉️ 𝑴𝒐𝒕𝒊𝒗𝒂𝒕𝒊𝒐𝒏
Compose objects into tree structures to represent part or whole of hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

🌍 𝑹𝒆𝒂𝒍-𝑾𝒐𝒓𝒍𝒅 𝑺𝒄𝒆𝒏𝒂𝒓𝒊𝒐
Imagine you're building a graphical editor. Users can create basic shapes like Text, Circle, etc., and combine them into complex images.
A basic solution might involve one class for simple objects and another for containers. But this forces clients to handle each differently, increasing complexity.

🎯 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 — 𝐂𝐨𝐦𝐩𝐨𝐬𝐢𝐭𝐞 𝐏𝐚𝐭𝐭𝐞𝐫𝐧
Composite pattern helps us to recursive composition so that clients are not required to make this distinction. This pattern has an abstract class for both primitives and their containers.
For instance, in the graphics system this abstract named Graphic which declares operation like Draw for graphical objects. It also declares operations that all composite objects share, such as Get Child, Add, Remove.
The Picture class defines a list of graphic objects and implements draw to call draw on its children. In addition, the picture implements child-related operations. Since the picture interface inherits from the Graphic interface, picture objects can compose other pictures recursively.

Image description

🧠 𝐖𝐡𝐞𝐧 𝐭𝐨 𝐔𝐬𝐞
✔️ When individual objects and object groups should be handled identically.
✔️ When tree structures or recursive hierarchies are involved.

💎 𝑹𝒆𝒍𝒂𝒕𝒆𝒅 𝑷𝒂𝒕𝒕𝒆𝒓𝒏𝒔
🔁 Chain of Responsibility often uses parent references.
🎨 Decorator works well with Composite to extend behavior.
🧬 Flyweight can reduce memory usage but removes parent references.
🔍 Iterator helps traverse composite structures.
🧭 Visitor centralizes operations across Composite and Leaf classes.

📂 𝑪𝒐𝒅𝒆 𝑬𝒙𝒂𝒎𝒑𝒍𝒆
👉 GitHub - https://lnkd.in/dy9h_VuA

💬 𝐘𝐨𝐮𝐫 𝐓𝐮𝐫𝐧!
❓𝐇𝐚𝐯𝐞 𝐲𝐨𝐮 𝐞𝐯𝐞𝐫 𝐮𝐬𝐞𝐝 𝐭𝐡𝐞 𝐂𝐨𝐦𝐩𝐨𝐬𝐢𝐭𝐞 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 𝐢𝐧 𝐲𝐨𝐮𝐫 𝐩𝐫𝐨𝐣𝐞𝐜𝐭𝐬?

hashtag#DesignPatterns hashtag#SoftwareEngineering hashtag#DevTips hashtag#CompositePattern

Top comments (0)