What is Composite Pattern?
The Composite Pattern is a structural design pattern that lets you treat individual objects and groups of objects in the same way.
It is mainly used for tree-like (hierarchical) structures.
Why Use Composite Pattern?
- Handle single objects and collections uniformly
- Simplify complex hierarchical structures
- Enable recursive operations
- Improve scalability
Real-Time Scenario
- Folder → contains files & subfolders
- Invoice → contains multiple items
- Product → single item or grouped items
👉 You can calculate total price the same way for both
Implementation
Step 1: Component Interface
public interface IComponent
{
decimal GetPrice();
}
Step 2: Leaf (Single Object)
public class Product : IComponent
{
private readonly decimal _price;
public Product(decimal price)
{
_price = price;
}
public decimal GetPrice() => _price;
}
Step 3: Composite (Group of Objects)
public class ProductGroup : IComponent
{
private readonly List<IComponent> _items = new();
public void Add(IComponent item)
{
_items.Add(item);
}
public decimal GetPrice()
{
return _items.Sum(x => x.GetPrice());
}
}
Usage Example
// Individual products
var item1 = new Product(500);
var item2 = new Product(300);
// Group (like invoice or cart)
var group = new ProductGroup();
group.Add(item1);
group.Add(item2);
// Nested group
var mainGroup = new ProductGroup();
mainGroup.Add(group);
mainGroup.Add(new Product(200));
Console.WriteLine(mainGroup.GetPrice()); // 1000
Key Concept
Instead of:
if(item is Product) { ... }
else if(item is ProductGroup) { ... }
We do:
item.GetPrice();
👉 Same method works for both single and group
Advantages
- ✔ Reduces complexity
- ✔ Improves flexibility
- ✔ Promotes reusable structures
- ✔ Easier maintenance
Disadvantages
- ✖ Can increase number of classes
- ✖ Harder to understand initially
- ✖ Over-engineering for simple apps
When to Use
- When dealing with tree/hierarchical structures
- When you want uniform treatment of objects
- When structure can grow dynamically
- When recursive operations are needed
Real Project Mapping (.NET + Angular)
| Feature | Usage |
|---|---|
| Invoice items | Composite |
| Shopping cart | Composite |
| Folder/file system | Composite |
| Menu structures | Composite |
Pro Tip (Advanced .NET Usage)
- Combine with DTOs for hierarchical APIs
- Useful in recursive UI rendering (Angular tree view)
- Works well with LINQ for aggregation
Summary
Composite Pattern helps you:
- Treat single and grouped objects uniformly
- Build hierarchical data structures
- Simplify recursive logic
👉 Perfect for invoice systems, carts, trees, nested data structures
Comments
Post a Comment