Design Patterns: Composite

The Composite Design Pattern consists of the allowing software that executes an operation in a collection of primitive and composite objects. The easiest example to think of is a file system, you can have a directory and it may have more directories and also files in them.

One example of a composite pattern structure would be:


Figure 1: Composite Pattern Structure

The following code prints elements on the screen in a hierarchical format without having to worry about the type of the object (for example, you could print a directory and file names without being concerned with whether the object is a directory or a file).

  1. public interface Component   
  2. {   
  3. void DoStuff(int indent);   
  4. }   
  5. public class Item : Component   
  6. {   
  7. public string Name { getset; }   
  8. public void DoStuff(int indent)   
  9. {   
  10. Console.Write(new String(' ', indent));   
  11. Console.WriteLine(Name);   
  12. }   
  13. }   
  14. public class Composite : Component   
  15. {   
  16. public Composite()   
  17. {   
  18. Components = new List  
  19. <Component>();   
  20. }   
  21. public IList  
  22.     <Component> Components { getset; }   
  23. public void DoStuff(int indent)   
  24. {   
  25. Console.Write(new String(' ', indent));   
  26. Console.WriteLine("  
  27.         <Group>");   
  28. foreach (var component in Components)   
  29. {   
  30. component.DoStuff(indent + 2);   
  31. }   
  32. }   
  33. }   
Results:
  1. <Group>   
  2. First   
  3. Second   
  4. <Group>   
  5. Third   
  6. <Group>   
  7. Fourth 
In games it could be used to generate a skill tree or used to calculate some sort of composite attack. I found one example of it being used in the attributes system of a RPG game.


Similar Articles