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)