The Composite design pattern composes objects into tree structures to represent part-whole hierarchies. This pattern lets clients treat individual object and compositions of objects uniformly.
组合模式将对象组合成tree结构代表部分-整体层次结构,这种模式允许客户端统一处理单个对象和组合对象。
UML Class Disgram
Component: This is going to be an abstract or interface containing the members that will be implemented by both Leaf and Composite Classess. If required then it can also implement some of behavior that is common to all objects in the composition and in that case we need to create the Component as an abstract class.That means the abstract class or interface acts as the base class for all the objects within the hierarchiy.
Leaf: This is going to be a class to present the leaf behavior in the composition.
Composite: The Composite defines the behavior of the Composite Components. THe Composite have children. The chidlren can be another composite component or can be a leaf component.
Client: The Client is the class that manipulates objects in the composition through the Component interface.
/// <summary> /// The base Component class declares the common operations for both simple and complex objects. /// </summary> public interface IComponent { void Add(IComponent component); void Remove(IComponent component); void Display(int depth); }Component
/// <summary> /// The Compoiste class represents the complex component that have children. /// The Composite objects delegate the actual work to their children and the combine the result. /// </summary> public class Composite : IComponent { public List<IComponent> children = new List<IComponent>(); public string Name; public Composite(string name) { this.Name = name; } public void Add(IComponent component) { children.Add(component); } public void Remove(IComponent component) { children.Remove(component); } public void Display(int depth) { Console.WriteLine(new string('-', depth) + Name); foreach (var component in children) { component.Display(depth + 2); } } }Composite
/// <summary> /// The Leaf class represents the end objects. /// A leaf can't have any children. /// The leaf object is the object which does the actual work. /// </summary> public class Leaf : IComponent { public string Name; public Leaf(string name) { this.Name = name; } public void Add(IComponent component) { Console.WriteLine("Cannot add to a leaf"); } public void Remove(IComponent component) { Console.WriteLine("Cannot remove from a leaf."); } public void Display(int depth) { Console.WriteLine(new string('-', depth) + Name); } }Leaf
When do we need to use the Composite Desgin Pattern in C#?
- we want to represent part-whole hierarchies of objects.
- we want to the client ignore the difference between the compositions of objects and individual objects.