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).
- public interface Component
- {
- void DoStuff(int indent);
- }
- public class Item : Component
- {
- public string Name { get; set; }
- public void DoStuff(int indent)
- {
- Console.Write(new String(' ', indent));
- Console.WriteLine(Name);
- }
- }
- public class Composite : Component
- {
- public Composite()
- {
- Components = new List
- <Component>();
- }
- public IList
- <Component> Components { get; set; }
- public void DoStuff(int indent)
- {
- Console.Write(new String(' ', indent));
- Console.WriteLine("
- <Group>");
- foreach (var component in Components)
- {
- component.DoStuff(indent + 2);
- }
- }
- }
Results:
- <Group>
- First
- Second
- <Group>
- Third
- <Group>
- 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.